package com.glink.manage.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.contants.BaseCodeConstants;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.common.CommonUtils;
import com.glink.manage.common.Constants;
import com.glink.manage.common.LogRecordUtils;
import com.glink.manage.common.PoiTools;
import com.glink.manage.domain.*;
import com.glink.manage.dto.constructionwork.ConstructionWorkSiteIdOrEquipObjIdDTO;
import com.glink.manage.dto.equip.PatrolIntelligentEquipBroadcastStatusDTO;
import com.glink.manage.dto.equip.PatrolIntelligentEquipDTO;
import com.glink.manage.dto.equip.PatrolIntelligentEquipPageDTO;
import com.glink.manage.dto.equip.channel.PatrolIntelligentEquipChannelDTO;
import com.glink.manage.dto.sip.AddDeviceDTO;
import com.glink.manage.dto.sip.DeleteDeviceDTO;
import com.glink.manage.dto.sip.UpdateDeviceDTO;
import com.glink.manage.dto.sip.UpdateStatusDTO;
import com.glink.manage.dto.video.*;
import com.glink.manage.mapper.PatrolIntelligentEquipMapper;
import com.glink.manage.service.*;
import com.glink.manage.vo.constructionwork.ConstructionWorkAndWorkSiteInfoVO;
import com.glink.manage.vo.equip.PatrolIntelligentEquipChannelVO;
import com.glink.manage.vo.equip.PatrolIntelligentEquipNvrVO;
import com.glink.manage.vo.equip.PatrolIntelligentEquipVO;
import com.glink.manage.vo.overview.IntelligentEquipVO;
import com.glink.manage.vo.sip.WVPResult;
import com.glink.manage.vo.user.UserBaseInfoVO;
import com.glink.manage.vo.video.*;
import com.glink.manage.vo.ws.BroadcastStatusVO;
import com.glink.manage.ws.WarnWebSocketService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author glink
 * @description: 智能设备台账实现类
 * @since 2024-07-01
 */
@Service
@Slf4j
public class PatrolIntelligentEquipServiceImpl extends ServiceImpl<PatrolIntelligentEquipMapper, PatrolIntelligentEquip> implements PatrolIntelligentEquipService {


    @Autowired
    private PatrolIntelligentEquipChannelService intelligentEquipChannelService;

    @Autowired
    private ConstructionWorkService constructionWorkService;

    @Autowired
    private ConstructionWorkSiteService constructionWorkSiteService;
    
    @Autowired
    private PersonManageService personManageService;

    @Autowired
    private OrgServiceImpl orgService;

    @Autowired
    private CodeService codeService;

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @Autowired
    private WarnWebSocketService warnWebSocketService;

    @Value("${proxySipServer.intranetProxySipCode:29176544766600095860}")//在内网sip服务配置文件中配置
    private String intranetProxySipCode;

    //外部网络sip服务地址：端口
    @Value("${sip.internalNetWorkSipServerAddress:https://192.168.1.31}")
    private String internalNetWorkSipServerAddress;

    @Value("${sip.internalNetWorkSipServerPort:18082}")
    private String internalNetWorkSipServerPort;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertIntelligentEquip(PatrolIntelligentEquipDTO dto, String remoteIp) throws GeneralSimpleException {
        
        if(StringUtils.isNotBlank(dto.getConstructionWorkSiteId())){
            // 校验场站授权
            constructionWorkSiteService.checkGrantByObjId(dto.getConstructionWorkSiteId());
        }
        
        PatrolIntelligentEquip equip = new PatrolIntelligentEquip();
        BeanUtil.copyProperties(dto, equip, CopyOptions.create().setIgnoreNullValue(true));
        if (StringUtils.isEmpty(dto.getPatrolDeviceName())){
            equip.setPatrolDeviceName(dto.getPatrolDeviceCode());
        }
        equip.setObjId(BaseCommonUtils.generateUUID());
        //摄像机20位sip用户名
        String randomString = CommonUtils.getSipCode();
        equip.setSipCode(randomString);
        //通道列表
        List<PatrolIntelligentEquipChannel> saveChannelList = Lists.newArrayList();
        List<String> channelCodeList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(dto.getChannelDTOList())) {
            for (PatrolIntelligentEquipChannelDTO channelDTO : dto.getChannelDTOList()) {
                PatrolIntelligentEquipChannel channel = new PatrolIntelligentEquipChannel();
                BeanUtil.copyProperties(channelDTO, channel, CopyOptions.create().setIgnoreNullValue(true));
                channel.setObjId(BaseCommonUtils.generateUUID());
                channel.setEquipId(equip.getObjId());
                channel.setConstructionWorkId(equip.getConstructionWorkId());
                channel.setConstructionWorkSiteId(equip.getConstructionWorkSiteId());
                //20位视频通道编码ID
                channel.setChannelCode(randomString.substring(0, 10) + "131" + randomString.substring(13, 19) + channelDTO.getEquipChannelNumber());
                channelCodeList.add(channel.getChannelCode());
                saveChannelList.add(channel);
            }
        }
        boolean status = this.save(equip);
        if (status) {
            if (CollectionUtils.isNotEmpty(saveChannelList)) {
                status = this.intelligentEquipChannelService.saveBatch(saveChannelList);
            }
        }

        if (status) {
            //设备信息通知到外网sip服务
            CompletableFuture.runAsync(() -> {
                try {
                    Thread.sleep(1000);
                    PatrolIntelligentEquip patrolIntelligentEquip = this.getById(equip.getObjId());
                    if (Objects.nonNull(patrolIntelligentEquip)){
                        this.addInternetProxyMedia(patrolIntelligentEquip, channelCodeList);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            String userId = BaseCommonUtils.extractUserIdtByToken();
            UserBaseInfoVO userBaseInfoVO = userService.findById(userId);
            String logMsg = LogRecordUtils.createEquip(userBaseInfoVO.getUserName(), equip.getPatrolDeviceName());
            logService.addLogRecord(userId, userBaseInfoVO.getUserName(), BaseCodeConstants.CodeType_LogType.KEY_LogType04, logMsg, remoteIp);
        }
        return status;
    }


    /**
     * 数据下发
     *
     * @param equip            主数据
     * @param equipChannelList 通道数据
     */
    public void dataDistribute(PatrolIntelligentEquip equip, List<PatrolIntelligentEquipChannel> equipChannelList) {
        //数据下发
        CompletableFuture.runAsync(() -> {
            dataDistributeNotSync(equip, equipChannelList);
        });
    }

    @Override
    public void deleteProxyMedia(PatrolIntelligentEquip equip,List<String> channelCodeList) throws GeneralSimpleException{
        ConstructionWorkBean constructionWorkBean = constructionWorkService.getById(equip.getConstructionWorkId());
        if (Objects.nonNull(constructionWorkBean)) {
            DeleteDeviceDTO deviceDTO = new DeleteDeviceDTO();
            deviceDTO.setProxySipCode(intranetProxySipCode);
            deviceDTO.setSipCode(equip.getSipCode());
            deviceDTO.setChannelCodeList(channelCodeList);
            String url = internalNetWorkSipServerAddress + ":" + internalNetWorkSipServerPort + "/api/notify/proxyMediaServer/deleteDevice";
            String result = CommonUtils.sendPost(url,JSON.toJSONString(deviceDTO));
            if(StringUtils.isNotBlank(result)){
                WVPResult wvpResult = JSON.parseObject(result,WVPResult.class);
                if(Objects.nonNull(wvpResult) && !StringUtils.equals(wvpResult.getCode(), Constants.SipResultCode.SUCCESS_CODE)){
                    log.error("视频代理删除设备失败：{}",wvpResult.getMsg());
                    throw new GeneralSimpleException("600208");
                }
            }
        }
    }

/*    public static void main(String[] args) {
        PatrolIntelligentEquipModel patrolIntelligentEquipModel = new PatrolIntelligentEquipModel();
        PatrolIntelligentEquipDetail detail = new PatrolIntelligentEquipDetail();
        List<PatrolIntelligentEquipChannelDetail> channelDetailList = Lists.newArrayList();
        detail.setBayId("gfsaa");
        patrolIntelligentEquipModel.setEquipDetail(detail);
        patrolIntelligentEquipModel.setEquipChannelDetailList(channelDetailList);
        PatrolIntelligentEquipChannelDetail detail1 = new PatrolIntelligentEquipChannelDetail();
        detail1.setAreaId("fggssad");
        channelDetailList.add(detail1);
        PatrolIntelligentEquipChannelDetail detail2 = new PatrolIntelligentEquipChannelDetail();
        detail1.setAreaId("fggssa222d");
        channelDetailList.add(detail2);
        String s = CommonUtils.beanToXml(patrolIntelligentEquipModel, PatrolIntelligentEquipModel.class, "UTF-8");
        System.out.println(s);

    }*/

    @Async
    @Override
    public void dataDistributeByEquipId(String equipId) {
        PatrolIntelligentEquip intelligentEquip = this.lambdaQuery().eq(PatrolIntelligentEquip::getObjId, equipId).one();
        if (Objects.nonNull(intelligentEquip)) {
            intelligentEquip.setSyncStatus(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
            updateById(intelligentEquip);

            List<PatrolIntelligentEquipChannel> equipChannelList = this.intelligentEquipChannelService.lambdaQuery()
                    .eq(PatrolIntelligentEquipChannel::getEquipId, intelligentEquip.getObjId()).list();

            dataDistributeNotSync(intelligentEquip, equipChannelList);
        }
    }

    /**
     * 批量同步未同步成功的智能设备-摄像机
     */
    @Override
    public void batchSync() {

        List<PatrolIntelligentEquip> intelligentEquipList = this.baseMapper.findAllBySyncStatus(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);

        if (CollectionUtils.isNotEmpty(intelligentEquipList)) {
            intelligentEquipList.forEach(intelligentEquip -> {
                List<PatrolIntelligentEquipChannel> equipChannelList = this.intelligentEquipChannelService.lambdaQuery()
                        .eq(PatrolIntelligentEquipChannel::getEquipId, intelligentEquip.getObjId()).list();
                dataDistributeNotSync(intelligentEquip, equipChannelList);
            });
        }
    }

    /**
     * 更新同步状态信息
     *
     * @param objId        智能设备ID
     * @param syncStatus   同步状态
     * @param syncTime     同步时间
     * @param syncFailMsg  同步失败信息
     * @param syncFailTime 同步失败时间
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateSyncInfo(String objId, String syncStatus, Date syncTime, String syncFailMsg, Date syncFailTime) {
        this.baseMapper.updateSyncInfo(objId, syncStatus, syncTime, syncFailMsg, syncFailTime);
    }

    /**
     * 根据厂站和设备类型查询设备ID
     *
     * @param stationId  厂站ID
     * @param deviceType 设备类型
     * @return 设备ID
     */
    @Override
    public List<String> findPatrolDeviceCodeByStationIdAndDeviceType(String stationId, String deviceType) {

 /*       List<PatrolIntelligentEquip> intelligentEquipList = this.lambdaQuery()
                .eq(StringUtils.isNotEmpty(stationId), PatrolIntelligentEquip::getStationId, stationId)
                .eq(PatrolIntelligentEquip::getDeleteState, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .eq(StringUtils.isNotEmpty(deviceType), PatrolIntelligentEquip::getDeviceType, deviceType)
                .isNotNull(PatrolIntelligentEquip::getPatrolDeviceCode)
                .ne(PatrolIntelligentEquip::getPatrolDeviceCode, "")
                .list();
        if(CollectionUtils.isNotEmpty(intelligentEquipList)){
            return intelligentEquipList.stream().map(PatrolIntelligentEquip::getPatrolDeviceCode).distinct().collect(Collectors.toList());
        }*/

        return null;
    }

    @Override
    public void dataDistributeNotSync(PatrolIntelligentEquip equip, List<PatrolIntelligentEquipChannel> equipChannelList) {

    }

    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateStatusByIds(UpdateStatusDTO dto) {
        //离线设备
        if (CollectionUtils.isNotEmpty(dto.getOffLineCodeList())) {
            List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                    .in(PatrolIntelligentEquipChannel::getChannelCode, dto.getOffLineCodeList()).list();
            if (CollectionUtils.isNotEmpty(channelList)) {
                Set<String> equipIds = channelList.stream().map(PatrolIntelligentEquipChannel::getEquipId).collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(equipIds)) {
                    this.lambdaUpdate().in(PatrolIntelligentEquip::getObjId, equipIds)
                            .set(PatrolIntelligentEquip::getIsOnline, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02).update();
                }
            }
        }
        //在线设备
        if (CollectionUtils.isNotEmpty(dto.getOnLineCodeList())) {
            List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                    .in(PatrolIntelligentEquipChannel::getChannelCode, dto.getOnLineCodeList()).list();
            if (CollectionUtils.isNotEmpty(channelList)) {
                Set<String> equipIds = channelList.stream().map(PatrolIntelligentEquipChannel::getEquipId).collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(equipIds)) {
                    this.lambdaUpdate().in(PatrolIntelligentEquip::getObjId, equipIds)
                            .set(PatrolIntelligentEquip::getIsOnline, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01).update();
                }
            }
        }
        return true;
    }

    @Override
    public List<PatrolIntelligentEquipVoiceListVO> findVoiceListByArea(PatrolIntelligentEquipListDTO equipListDTO) {
        return Collections.emptyList();
    }

    @Override
    public String findStationIdByproductCode(String productCode) {
        return "";
    }

    /**
     * 根据区域查询声纹装置设备
     *
     * @param dto 智能设备查询条件
     * @return 声纹装置列表
     */
   /* @Override
    public List<PatrolIntelligentEquipVoiceListVO> findVoiceListByArea(PatrolIntelligentEquipListDTO dto) {
        if(StringUtils.isEmpty(dto.getAreaId()) && StringUtils.isEmpty(dto.getDeviceName())){
            return Lists.newArrayList();
        }

        List<PatrolIntelligentEquipVoiceListVO> equipListVOList = Lists.newArrayList();
        // 输入名称后，自动模糊搜索； 不输入，默认加载当前点位所在区域的所有声音采集器
        List<PatrolIntelligentEquip> intelligentEquipList = null;
        if(StringUtils.isNotBlank(dto.getDeviceName()) || StringUtils.isNotBlank(dto.getAreaId())){
            intelligentEquipList = this.lambdaQuery()
                    .eq(PatrolIntelligentEquip::getDeviceType, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType14)
                    .eq(PatrolIntelligentEquip::getRunStatus, BaseCodeConstants.CodeType_RunStatus.KEY_RunStatus02)
                    .eq(PatrolIntelligentEquip::getIsOnline, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                    .eq(PatrolIntelligentEquip::getDeleteState, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                    .eq(StringUtils.isNotEmpty(dto.getStationId()), PatrolIntelligentEquip::getStationId, dto.getStationId())
                    .eq(StringUtils.isEmpty(dto.getDeviceName()), PatrolIntelligentEquip::getAreaId, dto.getAreaId())
                    .like(StringUtils.isNotEmpty(dto.getDeviceName()), PatrolIntelligentEquip::getPatrolDeviceName, dto.getDeviceName())
                    .orderByAsc(PatrolIntelligentEquip::getCreateTime).orderByAsc(PatrolIntelligentEquip::getObjId)
                    .list();
        }
        

        // 如果是按区域查询，并且点位关联的是区域之外的摄像机，则返回对应的摄像机信息
        if(StringUtils.isNotBlank(dto.getMeasurePointId())){
            // 如果区域ID和点位ID都不为空，则此次查询的是点位所在区域的摄像机，此时需要补充点位本身关联的摄像机，这个摄像机可能是其它区域的
            MeasurePointBean measurePointBean = measurePointService.lambdaQuery().eq(MeasurePointBean::getObjId, dto.getMeasurePointId()).one();
            if(Objects.nonNull(measurePointBean) && StringUtils.isNotBlank(measurePointBean.getPatrolDeviceCode())){

                List<String> equipIdList = Lists.newArrayList();
                if(CollectionUtils.isNotEmpty(intelligentEquipList)) {
                    equipIdList = intelligentEquipList.stream().map(PatrolIntelligentEquip::getObjId).collect(Collectors.toList());
                }

                List<PatrolIntelligentEquip> tempIntelligentEquipList = this.lambdaQuery()
                        .eq(PatrolIntelligentEquip::getPatrolDeviceCode, measurePointBean.getPatrolDeviceCode())
                        .eq(StringUtils.isNotEmpty(dto.getStationId()), PatrolIntelligentEquip::getStationId, dto.getStationId())
                        .notIn(CollectionUtils.isNotEmpty(equipIdList), PatrolIntelligentEquip::getObjId, equipIdList)
                        .list();
                if(CollectionUtils.isNotEmpty(tempIntelligentEquipList)){
                    intelligentEquipList.addAll(tempIntelligentEquipList);
                }
            }
        }

        if(CollectionUtils.isNotEmpty(intelligentEquipList)){

            List<String> equipIdList = intelligentEquipList.stream().map(PatrolIntelligentEquip::getObjId).collect(Collectors.toList());

            List<EquipCoordinateVO> equipCoordinateVOList = equipCoordinateService.findEquipsCoordinateByEquipIds(equipIdList);
            Map<String, EquipCoordinateVO> equipCoordinateMap = Maps.newHashMap();
            if(CollectionUtils.isNotEmpty(equipCoordinateVOList)){
                equipCoordinateMap = equipCoordinateVOList.stream().collect(Collectors.toMap(EquipCoordinateVO::getEquipId, Function.identity()));
            }

            Map<String, EquipCoordinateVO> finalEquipCoordinateMap = equipCoordinateMap;
            intelligentEquipList.forEach(intelligentEquip -> {

                List<PatrolIntelligentEquipChannel> equipChannelList = intelligentEquipChannelService.lambdaQuery()
                        .eq(PatrolIntelligentEquipChannel::getEquipId, intelligentEquip.getObjId())
                        .orderByAsc(PatrolIntelligentEquipChannel::getEquipChannelNumber)
                        .orderByAsc(PatrolIntelligentEquipChannel::getObjId)
                        .list();
                // 有多外视频流的摄像机，需要显示多条数据，显示格式为 “{摄像机名}: {视频流编号}-{视频流类型}
                if(CollectionUtils.isNotEmpty(equipChannelList)){
                    if(equipChannelList.size() == 1){
                        PatrolIntelligentEquipChannel equipChannel = equipChannelList.get(0);
                        PatrolIntelligentEquipVoiceListVO listVO = new PatrolIntelligentEquipVoiceListVO();
                        BeanUtils.copyProperties(intelligentEquip, listVO);
                        BeanUtils.copyProperties(equipChannel, listVO);
                        listVO.setEquipId(intelligentEquip.getObjId());

                        if(finalEquipCoordinateMap.containsKey(intelligentEquip.getObjId())){
                            EquipCoordinateVO equipCoordinateVO = finalEquipCoordinateMap.get(intelligentEquip.getObjId());
                            if(Objects.nonNull(equipCoordinateVO)){
                                listVO.setLocateMode(equipCoordinateVO.getLocateMode());
                                listVO.setEquipCoordinate(equipCoordinateVO.getEquipCoordinate());
                            }
                        }

                        equipListVOList.add(listVO);
                    }else{
                        for (PatrolIntelligentEquipChannel equipChannel : equipChannelList) {
                            PatrolIntelligentEquipVoiceListVO listVO = new PatrolIntelligentEquipVoiceListVO();
                            BeanUtils.copyProperties(intelligentEquip, listVO);
                            BeanUtils.copyProperties(equipChannel, listVO);
                            listVO.setEquipId(intelligentEquip.getObjId());

                            if(finalEquipCoordinateMap.containsKey(intelligentEquip.getObjId())){
                                EquipCoordinateVO equipCoordinateVO = finalEquipCoordinateMap.get(intelligentEquip.getObjId());
                                if(Objects.nonNull(equipCoordinateVO)){
                                    listVO.setLocateMode(equipCoordinateVO.getLocateMode());
                                    listVO.setEquipCoordinate(equipCoordinateVO.getEquipCoordinate());
                                }
                            }
                            equipListVOList.add(listVO);
                        }
                    }
                }else{
                    PatrolIntelligentEquipVoiceListVO listVO = new PatrolIntelligentEquipVoiceListVO();
                    listVO.setEquipId(intelligentEquip.getObjId());
                    listVO.setPatrolDeviceName(intelligentEquip.getPatrolDeviceName());
                    listVO.setPatrolDeviceCode(intelligentEquip.getPatrolDeviceCode());

                    if(finalEquipCoordinateMap.containsKey(intelligentEquip.getObjId())){
                        EquipCoordinateVO equipCoordinateVO = finalEquipCoordinateMap.get(intelligentEquip.getObjId());
                        if(Objects.nonNull(equipCoordinateVO)){
                            listVO.setLocateMode(equipCoordinateVO.getLocateMode());
                            listVO.setEquipCoordinate(equipCoordinateVO.getEquipCoordinate());
                        }
                    }
                    equipListVOList.add(listVO);
                }
            });
        }

        return equipListVOList;
    }*/

 /*   @Override
    public String findStationIdByproductCode(String productCode) {

        PatrolIntelligentEquip intelligentEquip = this.lambdaQuery().eq(PatrolIntelligentEquip::getProductCode, productCode).last(Constants.LAST_SQL).one();
        if(Objects.nonNull(intelligentEquip)){
            return intelligentEquip.getStationId();
        }

        return null;
    }
*/

    /**
     * 根据智能设备编码查询智能设备名称
     *
     * @param patrolDeviceCodeSet 智能设备编码
     * @return 智能设备名称
     */
    @Override
    public Map<String, String> findNameByPatrolDeviceCode(Set<String> patrolDeviceCodeSet) {
        Map<String, String> equipNameMap = Maps.newConcurrentMap();
        List<PatrolIntelligentEquip> intelligentEquipList = this.lambdaQuery().in(PatrolIntelligentEquip::getPatrolDeviceCode, patrolDeviceCodeSet).list();
        if (CollectionUtils.isNotEmpty(intelligentEquipList)) {
            intelligentEquipList.parallelStream().forEach(intelligentEquip -> {
                patrolDeviceCodeSet.remove(intelligentEquip.getPatrolDeviceCode());
                equipNameMap.put(intelligentEquip.getPatrolDeviceCode(), intelligentEquip.getPatrolDeviceName());
            });
        }

        if (CollectionUtils.isNotEmpty(patrolDeviceCodeSet)) {
            List<PatrolIntelligentEquip> delIntelligentEquipList = this.baseMapper.findPatrolDeviceNameByPatrolDeviceCodeIn(patrolDeviceCodeSet);
            if (CollectionUtils.isNotEmpty(delIntelligentEquipList)) {
                delIntelligentEquipList.parallelStream().forEach(intelligentEquip -> {
                    equipNameMap.put(intelligentEquip.getPatrolDeviceCode(), intelligentEquip.getPatrolDeviceName());
                });
            }
        }

        return equipNameMap;
    }

    /*  @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
      public void dataDistributeNotSync(PatrolIntelligentEquip equip, List<PatrolIntelligentEquipChannel> equipChannelList){
          String syncFailMsg = "";
          try {
              PatrolIntelligentEquipModel patrolIntelligentEquipModel = new PatrolIntelligentEquipModel();
              PatrolIntelligentEquipDetail detail = new PatrolIntelligentEquipDetail();
              BeanUtil.copyProperties(equip, detail);

              String edgeCode = "";
              // 厂站CODE
              if(StringUtils.isNotBlank(detail.getStationId())){
                  StationVO stationVO = stationService.findById(detail.getStationId());
                  if(Objects.nonNull(stationVO)){
                      detail.setStationCode(stationVO.getStationCode());
                      edgeCode = stationVO.getEdgeNodeIp();
                  }
              }
              patrolIntelligentEquipModel.setEquipDetail(detail);

              if(CollectionUtils.isNotEmpty(equipChannelList)){
                  List<PatrolIntelligentEquipChannelDetail> channelDetailList = Lists.newArrayList();
                  equipChannelList.forEach(equipChannel -> {
                      PatrolIntelligentEquipChannelDetail channelDetail = new PatrolIntelligentEquipChannelDetail();
                      BeanUtil.copyProperties(equipChannel, channelDetail);
                      channelDetailList.add(channelDetail);
                  });
                  patrolIntelligentEquipModel.setEquipChannelDetailList(channelDetailList);
              }

              // 预置位
              List<IntelligentEquipPresetBaseVO> equipPresetBaseVOList = intelligentEquipPresetService.findByEquipId(detail.getObjId());
              if(CollectionUtils.isNotEmpty(equipPresetBaseVOList)){
                  List<PatrolIntelligentEquipPresetDetail> presetDetailList = Lists.newArrayList();
                  equipPresetBaseVOList.forEach(equipPresetBaseVO -> {
                      PatrolIntelligentEquipPresetDetail presetDetail = new PatrolIntelligentEquipPresetDetail();
                      BeanUtils.copyProperties(equipPresetBaseVO, presetDetail);
                      presetDetail.setObjId(equipPresetBaseVO.getPresetId());
                      presetDetailList.add(presetDetail);
                  });
                  patrolIntelligentEquipModel.setEquipPresetDetailList(presetDetailList);
              }

              syncFailMsg = callRemoteModel.intelligentEquip(edgeCode, patrolIntelligentEquipModel);
          }catch (Exception e){
              e.printStackTrace();
              log.error("智能设备模型同步失败");
              syncFailMsg = "智能设备模型同步异常" + e.getMessage();
          }

          if(StringUtils.isNotEmpty(syncFailMsg)){
              updateSyncInfo(equip.getObjId(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02, CardUtil.date(), syncFailMsg, CardUtil.date());
          }

      }
      */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateIntelligentEquip(PatrolIntelligentEquipDTO dto, String remoteIp) throws GeneralSimpleException {
        if(StringUtils.isNotBlank(dto.getConstructionWorkSiteId())){
            // 校验场站授权
            constructionWorkSiteService.checkGrantByObjId(dto.getConstructionWorkSiteId());
        }
        //PatrolIntelligentEquip equip = null;
        if (StringUtils.isNotBlank(dto.getObjId())) {
            PatrolIntelligentEquip equip = this.getById(dto.getObjId());
            if (Objects.nonNull(equip)) {
                
                //sip用户名如果为空则需要新增
                if ((StringUtils.equals(equip.getDeviceType(), BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType10) ||
                        StringUtils.equals(equip.getDeviceType(), BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType11)) &&
                        StringUtils.isBlank(equip.getSipCode())) {
                    equip.setSipCode(CommonUtils.getSipCode());
                }
                String oldEquipName = equip.getPatrolDeviceName();
                String oldAgreement = equip.getAgreement();
                // 判断智能设备的设备编码是否进行了变更，如果变更，需要进行响应的更新
                String oldPatrolDeviceCode = equip.getPatrolDeviceCode();
                String oldPatrolDeviceName = equip.getPatrolDeviceName();
                String newPatrolDeviceCode = dto.getPatrolDeviceCode();
                String newPatrolDeviceName = dto.getPatrolDeviceName();
                boolean isUpdateMeasurePoint = false;
                if (StringUtils.isNotBlank(oldPatrolDeviceCode) && (!StringUtils.equals(oldPatrolDeviceCode, newPatrolDeviceCode) || !StringUtils.equals(oldPatrolDeviceName, newPatrolDeviceName))) {
                    isUpdateMeasurePoint = true;
                }

                BeanUtil.copyProperties(dto, equip, CopyOptions.create().setIgnoreNullValue(true));
                //通道列表
                List<String> channelCodeList = Lists.newArrayList();
                List<String> ids = Lists.newArrayList();
                List<PatrolIntelligentEquipChannel> saveChannelList = Lists.newArrayList();
                List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                        .eq(PatrolIntelligentEquipChannel::getEquipId, dto.getObjId()).list();
                if (CollectionUtils.isNotEmpty(dto.getChannelDTOList())) {
                    for (PatrolIntelligentEquipChannelDTO channelDTO : dto.getChannelDTOList()) {
                        PatrolIntelligentEquipChannel channel = new PatrolIntelligentEquipChannel();
                        BeanUtil.copyProperties(channelDTO, channel);
                        if (StringUtils.isBlank(channelDTO.getObjId())) {
                            channel.setObjId(BaseCommonUtils.generateUUID());
                        } else {
                            ids.add(channelDTO.getObjId());
                        }
                        //设置新的通道编码ID
                        String newCode = equip.getSipCode().substring(0, 10) + "131" + equip.getSipCode().substring(13, 19);
                        channel.setChannelCode(newCode + channelDTO.getEquipChannelNumber());

                        channelCodeList.add(channel.getChannelCode());
                        channel.setEquipId(dto.getObjId());
                        channel.setConstructionWorkId(equip.getConstructionWorkId());
                        channel.setConstructionWorkSiteId(equip.getConstructionWorkSiteId());
                        saveChannelList.add(channel);
                    }
                } else {
                    this.intelligentEquipChannelService.lambdaUpdate().eq(PatrolIntelligentEquipChannel::getEquipId, equip.getObjId()).remove();
                }
                boolean status = this.updateById(equip);
                if (status) {
                    if (CollectionUtils.isNotEmpty(saveChannelList)) {
                        List<String> allIds = channelList.stream().map(PatrolIntelligentEquipChannel::getObjId).collect(Collectors.toList());
                        //需要删除的通道
                        List<String> deleteIds = allIds.stream().filter(item -> !ids.contains(item)).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(deleteIds)) {
                            this.intelligentEquipChannelService.lambdaUpdate().in(PatrolIntelligentEquipChannel::getObjId, deleteIds).remove();

                        }
                        status = this.intelligentEquipChannelService.saveOrUpdateBatch(saveChannelList);
                    }
                }

                if (status) {
                    //设备信息通知到外网sip服务
                    CompletableFuture.runAsync(() -> {
                        try {
                            Thread.sleep(1000);
                            PatrolIntelligentEquip finalEquip = equip;
                            if (!StringUtils.equals(oldAgreement, dto.getAgreement())) {
                                //摄像机接入协议更改,通知外网 sip服务
                                this.updateProxyMedia(oldAgreement, finalEquip, channelCodeList);
                            } else {
                                //添加设备信息到外网 sip服务
                                this.addInternetProxyMedia(equip, channelCodeList);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    });
                    String userId = BaseCommonUtils.extractUserIdtByToken();
                    UserBaseInfoVO userBaseInfoVO = userService.findById(userId);
                    String logMsg = LogRecordUtils.updateEquip(userBaseInfoVO.getUserName(), oldEquipName);
                    logService.addLogRecord(userId, userBaseInfoVO.getUserName(), BaseCodeConstants.CodeType_LogType.KEY_LogType04, logMsg, remoteIp);
                }
            }
        }

        return true;
    }

    @Override
    public IPage<PatrolIntelligentEquipVO> findPageEquip(PatrolIntelligentEquipPageDTO dto)throws GeneralSimpleException {
        IPage<PatrolIntelligentEquipVO> result = new Page<>();
        Page<PatrolIntelligentEquip> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();

        boolean headOffice = userService.checkHeadOffice();
        List<String> orgIdList = null;
        List<String> workIdList = Lists.newArrayList();
        if(!headOffice){
            // 是否项目部管理员,如果是项目部管理员，优先以项目部管理员权限为主
            boolean projectDepartment = userService.checkProjectDepartment();
            boolean generalContractingUnit = false;
            if(!projectDepartment){
                // 是否总包单位管理员
                // 总包单位管理员，根据总包的工程查询工程信息
                generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){

                    workIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId();
                    
                    if(CollectionUtils.isEmpty(workIdList)){
                        log.info("摄像机查询，没有查询到总包的工程");
                        return new Page<>(dto.getPage(), dto.getSize());
                    }
                }
            }
            
            // 不是总包单位，则根据单位权限查询工程信息
            if(!generalContractingUnit){
                orgIdList = orgService.getDataPermissionOrgId();
                if(CollectionUtils.isEmpty(orgIdList)){
                    return new Page<>(dto.getPage(), dto.getSize());
                }
                workIdList = constructionWorkService.findWorkIdByProjectDepartmentObjIdIn(orgIdList);
            }
           
            if(CollectionUtils.isEmpty(workIdList)){
                return new Page<>(dto.getPage(), dto.getSize());
            }

            wrapper.in(PatrolIntelligentEquip::getConstructionWorkId, workIdList);
        }

        if (StringUtils.isNotBlank(dto.getObjId())) {
            wrapper.eq(PatrolIntelligentEquip::getObjId, dto.getObjId());
        }

        //所属项目部
        if (StringUtils.isNotBlank(dto.getDeptId())){
            //查询当前项目部下的所有的工程
            List<String> deptWorkIdList = constructionWorkService.findWorkIdByProjectDepartmentObjId(dto.getDeptId());
            if (CollectionUtils.isNotEmpty(deptWorkIdList)) {
                wrapper.in(PatrolIntelligentEquip::getConstructionWorkId, deptWorkIdList);
            }
        }

        //所属工程
        if (StringUtils.isNotBlank(dto.getConstructionWorkId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkId, dto.getConstructionWorkId());
        }

        //所属施工现场
        if (StringUtils.isNotBlank(dto.getConstructionWorkSiteId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkSiteId, dto.getConstructionWorkSiteId());
        }
        //模糊查询
        if (StringUtils.isNotBlank(dto.getSearchName())) {
            wrapper.and(w -> w.like(PatrolIntelligentEquip::getPatrolDeviceName, dto.getSearchName())
                    .or()
                    .like(PatrolIntelligentEquip::getPatrolDeviceCode, dto.getSearchName()));
        }
        //设备类型
        if (StringUtils.isNotBlank(dto.getDeviceType())) {
            wrapper.eq(PatrolIntelligentEquip::getDeviceType, dto.getDeviceType());
        }
        //使用类型
        if (StringUtils.isNotBlank(dto.getUseMode())) {
            wrapper.eq(PatrolIntelligentEquip::getUseMode, dto.getUseMode());
        }
        //运行状态
        if (StringUtils.isNotBlank(dto.getRunStatus())) {
            wrapper.eq(PatrolIntelligentEquip::getRunStatus, dto.getRunStatus());
        }
        //视频类型
        if (StringUtils.isNotBlank(dto.getVideoMode())) {
            wrapper.eq(PatrolIntelligentEquip::getVideoMode, dto.getVideoMode());
        }
        //是否在线
        if (StringUtils.isNotBlank(dto.getIsOnline())) {
            wrapper.eq(PatrolIntelligentEquip::getIsOnline, dto.getIsOnline());
        }
        //所属品牌
        if (StringUtils.isNotBlank(dto.getBrand())) {
            wrapper.eq(PatrolIntelligentEquip::getBrand, dto.getBrand());
        }
        wrapper.eq(PatrolIntelligentEquip::getDeviceType,BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType10);
        wrapper.orderByDesc(PatrolIntelligentEquip::getCreateTime);
        IPage<PatrolIntelligentEquip> iPage = this.page(page, wrapper);
        BeanUtil.copyProperties(iPage, result);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            result.setRecords(iPage.getRecords().stream().map(item -> {
                PatrolIntelligentEquipVO vo = new PatrolIntelligentEquipVO();
                BeanUtil.copyProperties(item, vo);
                findInfo(vo);
                return vo;
            }).collect(Collectors.toList()));
        }
        return result;
    }

    @Override
    public IPage<PatrolIntelligentEquipNvrVO> findPageNvr(PatrolIntelligentEquipNvrPageDTO dto)throws GeneralSimpleException {
        IPage<PatrolIntelligentEquipNvrVO> result = new Page<>();
        Page<PatrolIntelligentEquip> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();

        boolean headOffice = userService.checkHeadOffice();
        List<String> orgIdList = null;
        List<String> workIdList = Lists.newArrayList();
        if(!headOffice){
            // 是否项目部管理员,如果是项目部管理员，优先以项目部管理员权限为主
            boolean projectDepartment = userService.checkProjectDepartment();
            boolean generalContractingUnit = false;
            if(!projectDepartment){
                // 是否总包单位管理员
                // 总包单位管理员，根据总包的工程查询工程信息
                generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){
                    workIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId();
                    if(CollectionUtils.isEmpty(workIdList)){
                        log.info("摄像机查询，没有查询到总包的工程");
                        return new Page<>(dto.getPage(), dto.getSize());
                    }
              
                }
            }

            // 不是总包单位，则根据单位权限查询工程信息
            if(!generalContractingUnit) {
                orgIdList = orgService.getDataPermissionOrgId();
                if (CollectionUtils.isEmpty(orgIdList)) {
                    return new Page<>(dto.getPage(), dto.getSize());
                }
                workIdList = constructionWorkService.findWorkIdByProjectDepartmentObjIdIn(orgIdList);
            }
            if(CollectionUtils.isEmpty(workIdList)){
                return new Page<>(dto.getPage(), dto.getSize());
            }

            wrapper.in(PatrolIntelligentEquip::getConstructionWorkId, workIdList);
        }

        //所属项目部
        if (StringUtils.isNotBlank(dto.getDeptId())){
            //查询当前项目部下的所有的工程
            List<String> deptWorkIdList = constructionWorkService.findWorkIdByProjectDepartmentObjId(dto.getDeptId());
            if (CollectionUtils.isNotEmpty(deptWorkIdList)) {
                wrapper.in(PatrolIntelligentEquip::getConstructionWorkId, deptWorkIdList);
            }
        }

        if (StringUtils.isNotBlank(dto.getObjId())) {
            wrapper.eq(PatrolIntelligentEquip::getObjId, dto.getObjId());
        }
        //所属工程
        if (StringUtils.isNotBlank(dto.getConstructionWorkId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkId, dto.getConstructionWorkId());
        }

        //所属施工现场
        if (StringUtils.isNotBlank(dto.getConstructionWorkSiteId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkSiteId, dto.getConstructionWorkSiteId());
        }

        //模糊查询
        if (StringUtils.isNotBlank(dto.getSearchName())) {
            wrapper.and(w -> w.like(PatrolIntelligentEquip::getPatrolDeviceName, dto.getSearchName())
                    .or()
                    .like(PatrolIntelligentEquip::getPatrolDeviceCode, dto.getSearchName()));
        }
        //品牌
        if (StringUtils.isNotBlank(dto.getBrand())) {
            wrapper.eq(PatrolIntelligentEquip::getBrand, dto.getBrand());
        }
        //运行状态
        if (StringUtils.isNotBlank(dto.getRunStatus())) {
            wrapper.eq(PatrolIntelligentEquip::getRunStatus, dto.getRunStatus());
        }
        wrapper.eq(PatrolIntelligentEquip::getDeviceType, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType11);
        wrapper.orderByDesc(PatrolIntelligentEquip::getCreateTime);
        IPage<PatrolIntelligentEquip> iPage = this.page(page, wrapper);
        BeanUtil.copyProperties(iPage, result);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            result.setRecords(iPage.getRecords().stream().map(item -> {
                PatrolIntelligentEquipNvrVO vo = new PatrolIntelligentEquipNvrVO();
                BeanUtil.copyProperties(item, vo);
                //所属工程
                if (StringUtils.isNotBlank(vo.getConstructionWorkId())) {
                    ConstructionWorkBean constructionWorkBean = constructionWorkService.getById(vo.getConstructionWorkId());
                    if (Objects.nonNull(constructionWorkBean)) {
                        vo.setConstructionWorkName(constructionWorkBean.getWorkName());
                    }
                }

                //所属施工现场
                if (StringUtils.isNotBlank(vo.getConstructionWorkSiteId())) {
                    vo.setConstructionWorkSiteName(constructionWorkSiteService.findNameByObjId(vo.getConstructionWorkSiteId()));
                }

                //查询已接入摄像机数
                vo.setEquipNum(this.intelligentEquipChannelService.lambdaQuery().eq(PatrolIntelligentEquipChannel::getBelongEquipId, vo.getObjId()).count());
                //检查投运日期
                if (Objects.nonNull(vo.getOutageTime()) && Objects.nonNull(vo.getRunTime())) {
                    if (DateUtil.date().isAfterOrEquals(vo.getRunTime()) && DateUtil.date().isBeforeOrEquals(vo.getOutageTime())) {
                        vo.setRunStatus(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                    }
                }
                return vo;
            }).collect(Collectors.toList()));
        }
        return result;
    }

    /**
     * 根据类型分页智能设备
     *
     * @param dto
     * @return IPage<PatrolIntelligentEquipVO>
     */
    @Override
    public IPage<PatrolIntelligentEquipVO> findPageEquipByDeviceType(PatrolIntelligentEquipSearchDTO dto) {
        IPage<PatrolIntelligentEquipVO> result = new Page<>();
       /* Page<PatrolIntelligentEquip> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();
        //所属厂站
        wrapper.eq(PatrolIntelligentEquip::getStationId, dto.getStationId());
        //名称模糊查询
        if(StringUtils.isNotBlank(dto.getSearchName())){
            wrapper.and(w -> w.like(PatrolIntelligentEquip::getPatrolDeviceName, dto.getSearchName())
                    .or()
                    .like(PatrolIntelligentEquip::getPatrolDeviceCode, dto.getSearchName()));
        }
        //设备类型
        if(CollUtil.isNotEmpty(dto.getDeviceTypes())){
            wrapper.in(PatrolIntelligentEquip::getDeviceType,dto.getDeviceTypes());
        }
        wrapper.orderByDesc(PatrolIntelligentEquip::getCreateTime);
        IPage<PatrolIntelligentEquip> iPage = this.page(page, wrapper);
        BeanUtil.copyProperties(iPage,result);
        if(CollectionUtils.isNotEmpty(iPage.getRecords())){
            result.setRecords(iPage.getRecords().stream().map(item ->{
                PatrolIntelligentEquipVO vo = new PatrolIntelligentEquipVO();
                BeanUtil.copyProperties(item,vo);
                return vo;
            }).collect(Collectors.toList()));
        }*/
        return result;
    }

    @Override
    public PatrolIntelligentEquipVO findById(String objId) {
        PatrolIntelligentEquipVO vo = new PatrolIntelligentEquipVO();
        PatrolIntelligentEquip equip = this.getById(objId);
        if (Objects.nonNull(equip)) {
            BeanUtil.copyProperties(equip, vo);
            findInfo(vo);
        }
        return vo;
    }

    @Override
    public PatrolIntelligentEquipNvrVO findNvrById(String objId) {
        PatrolIntelligentEquipNvrVO vo = new PatrolIntelligentEquipNvrVO();
        PatrolIntelligentEquip equip = this.getById(objId);
        if (Objects.nonNull(equip)) {
            BeanUtil.copyProperties(equip, vo);
            //所属工程
            if (StringUtils.isNotBlank(vo.getConstructionWorkId())) {
                ConstructionWorkBean constructionWorkBean = constructionWorkService.getById(vo.getConstructionWorkId());
                if (Objects.nonNull(constructionWorkBean)) {
                    vo.setConstructionWorkName(constructionWorkBean.getWorkName());
                }
            }
            //所属施工现场
            if (StringUtils.isNotBlank(vo.getConstructionWorkSiteId())) {
                vo.setConstructionWorkSiteName(constructionWorkSiteService.findNameByObjId(vo.getConstructionWorkSiteId()));
            }
            //查询已接入摄像机数
            vo.setEquipNum(this.intelligentEquipChannelService.lambdaQuery().eq(PatrolIntelligentEquipChannel::getBelongEquipId, vo.getObjId()).count());
        }
        return vo;
    }

    @Override
    public PatrolIntelligentEquipSimpleVO findByChannelCode(String channelCode) {
        List<PatrolIntelligentEquipChannel> channelList = intelligentEquipChannelService.lambdaQuery().eq(PatrolIntelligentEquipChannel::getChannelCode, channelCode).list();
      /*  if (CollUtil.isNotEmpty(channelList)) {
            List<PatrolIntelligentEquip> intelligentEquipList = this.lambdaQuery().eq(PatrolIntelligentEquip::getObjId, channelList.get(0).getEquipId())
                    .in(PatrolIntelligentEquip::getDeviceType, Arrays.asList(BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType13, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType15)).list();
            if (CollUtil.isNotEmpty(intelligentEquipList)) {
                PatrolIntelligentEquip intelligentEquip = intelligentEquipList.get(0);
                PatrolIntelligentEquipSimpleVO equipSimpleVO = new PatrolIntelligentEquipSimpleVO();
                equipSimpleVO.setObjId(intelligentEquip.getObjId());
                equipSimpleVO.setStationId(intelligentEquip.getStationId());
                equipSimpleVO.setPatrolDeviceCode(intelligentEquip.getPatrolDeviceCode());
                equipSimpleVO.setProductCode(intelligentEquip.getProductCode());
                equipSimpleVO.setPatrolDeviceName(intelligentEquip.getPatrolDeviceName());
                return equipSimpleVO;
            }
        }*/
        return null;
    }

    @Override
    public List<PatrolIntelligentEquipTreeVO> findByWorkSiteId(String workSiteId, String runStatus, String isOnline,String deviceType,String name) {
        List<PatrolIntelligentEquipTreeVO> result = Lists.newArrayList();

        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(runStatus)) {
            wrapper.eq(PatrolIntelligentEquip::getRunStatus, runStatus);
        }
        if (StringUtils.isNotBlank(workSiteId)) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkSiteId, workSiteId);
        }
        if (StringUtils.isNotBlank(isOnline)) {
            wrapper.eq(PatrolIntelligentEquip::getIsOnline, isOnline);
        }
        if (StringUtils.isNotBlank(deviceType)){
            wrapper.eq(PatrolIntelligentEquip::getDeviceType, deviceType);
        }
        if (StringUtils.isNotBlank(name)){
            wrapper.like(PatrolIntelligentEquip::getPatrolDeviceName, name);
        }
        wrapper.orderByAsc(PatrolIntelligentEquip::getCreateTime);
        List<PatrolIntelligentEquip> equipList = this.list(wrapper);
        if (CollectionUtils.isNotEmpty(equipList)) {
            result = equipList.stream().map(item -> {
                PatrolIntelligentEquipTreeVO vo = new PatrolIntelligentEquipTreeVO();
                vo.setObjId(item.getObjId());
                vo.setObjName(item.getPatrolDeviceName());
                vo.setUseMode(item.getUseMode());
                vo.setIsOnline(item.getIsOnline());
                vo.setType("03");
                vo.setConstructionWorkObjId(item.getConstructionWorkId());
                vo.setConstructionWorkSiteObjId(item.getConstructionWorkSiteId());
                //查询通道信息
                List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                        .eq(PatrolIntelligentEquipChannel::getEquipId, item.getObjId())
                        .orderByAsc(PatrolIntelligentEquipChannel::getEquipChannelNumber).list();
                if (CollectionUtils.isNotEmpty(channelList)) {
                    List<PatrolIntelligentEquipTreeVO> idNameList = Lists.newArrayList();
                    for (PatrolIntelligentEquipChannel c : channelList) {
                        PatrolIntelligentEquipTreeVO idName = new PatrolIntelligentEquipTreeVO();
                        idName.setObjId(c.getObjId());
                        idName.setType("04");
                        idName.setChannelNumber(c.getChannelNumber());
                        idName.setEquipChannelNumber(c.getEquipChannelNumber());
                        idName.setBelongEquipId(c.getBelongEquipId());
                        idName.setEquipId(c.getEquipId());
                        idName.setUseMode(item.getUseMode());
                        idName.setUrlType(c.getUrlType());
//                        idName.setSerialNumber(c.getSerialNumber());
                        idName.setIsOnline(item.getIsOnline());
                        idName.setPtz(item.getPtz());
                        idName.setNight(item.getNight());
                        idName.setWiper(item.getWiper());
                        idName.setChannelCode(c.getChannelCode());
                        idName.setChannelCodeNvr(c.getChannelCodeNvr());
                        idNameList.add(idName);
                    }
                    vo.setChildrenList(idNameList);
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return result;
    }

    public List<PatrolIntelligentEquipVoiceTreeVO> findTreeByAreaId(String areaId, String runStatus, String isOnline) {
        List<PatrolIntelligentEquipVoiceTreeVO> result = Lists.newArrayList();

        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(runStatus)) {
            wrapper.eq(PatrolIntelligentEquip::getRunStatus, runStatus);
        }
      /*  if(StringUtils.isNotBlank(areaId)){
            wrapper.eq(PatrolIntelligentEquip::getAreaId,areaId);
        }*/
        if (StringUtils.isNotBlank(isOnline)) {
            wrapper.eq(PatrolIntelligentEquip::getIsOnline, isOnline);
        }
        wrapper.eq(PatrolIntelligentEquip::getDeviceType, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType14);
        wrapper.eq(PatrolIntelligentEquip::getRunStatus, BaseCodeConstants.CodeType_RunStatus.KEY_RunStatus02);
        wrapper.orderByAsc(PatrolIntelligentEquip::getCreateTime);
        List<PatrolIntelligentEquip> equipList = this.list(wrapper);
        if (CollectionUtils.isNotEmpty(equipList)) {
            result = equipList.stream().map(item -> {
                PatrolIntelligentEquipVoiceTreeVO vo = new PatrolIntelligentEquipVoiceTreeVO();
                vo.setObjId(item.getObjId());
                vo.setObjName(item.getPatrolDeviceName());
                vo.setIsOnline(item.getIsOnline());
                vo.setPatrolDeviceCode(item.getPatrolDeviceCode());
                vo.setType("03");
                return vo;
            }).collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public List<PatrolIntelligentEquipVO> findByAreaId(PatrolIntelligentEquipInspectionDTO dto) {
        List<PatrolIntelligentEquipVO> result = Lists.newArrayList();

        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(dto.getSearchName())) {
            wrapper.like(PatrolIntelligentEquip::getPatrolDeviceName, dto.getSearchName());
        }
        /* wrapper.eq(PatrolIntelligentEquip::getAreaId,dto.getAreaId());*/
        List<PatrolIntelligentEquip> equipList = this.list(wrapper);
        if (CollectionUtils.isNotEmpty(equipList)) {
            result = equipList.stream().map(item -> {
                PatrolIntelligentEquipVO vo = new PatrolIntelligentEquipVO();
                BeanUtil.copyProperties(item, vo);
                findInfo(vo);
                return vo;
            }).collect(Collectors.toList());
        }
        return result;
    }

    /**
     * 查询区域下摄像机数
     * @param areaId 区域ID
     */
   /* @Override
    public Integer countByAreaId(String areaId) {
        return this.lambdaQuery().eq(PatrolIntelligentEquip::getAreaId, areaId).count();
    }*/

    /**
     * 查询间隔下摄像机数
     * @param bayIds 间隔ID
     */
   /* @Override
    public Integer countByBayIds(List<String> bayIds) {
        return this.lambdaQuery().in(PatrolIntelligentEquip::getBayId, bayIds).count();
    }*/

    /**
     * 查询厂站下各类摄像机数
     *
     * @param stationId 厂站ID
     */
    @Override
    public List<IntelligentEquipVO> findIntelligentEquipOverview(String stationId) {
        /* List<PatrolIntelligentEquip> equipAllList = this.lambdaQuery().eq(PatrolIntelligentEquip::getStationId, stationId).list();*/
        List<IntelligentEquipVO> intelligentEquipList = new ArrayList<>();
        /* if (CollUtil.isNotEmpty(equipAllList)) {
            List<PatrolIntelligentEquip> cameraEquipList = equipAllList.stream().filter(c -> StrUtil.isNotBlank(c.getUseMode())).collect(Collectors.toList());
            //统计摄像机
            List<String> deviceCodes = cameraEquipList.stream().filter(e -> StrUtil.isNotBlank(e.getPatrolDeviceCode())).map(PatrolIntelligentEquip::getPatrolDeviceCode).collect(Collectors.toList());
            List<MeasurePointBaseVO> allPointList = measurePointService.getPointsByDeviceCodes(stationId, null, BaseCodeConstants.CodeType_PointType.KEY_PointType01);
            List<MeasurePointBaseVO> pointList = measurePointService.getPointsByDeviceCodes(stationId, deviceCodes, BaseCodeConstants.CodeType_PointType.KEY_PointType01);
            intelligentEquipList.add(buildIntelligentEquipVO(EquipClassDict.CAMERA.getVal(), cameraEquipList, pointList, allPointList, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType10));
            //统计各类型摄像机
            Map<String, List<PatrolIntelligentEquip>> useModeMap = cameraEquipList.stream().collect(Collectors.groupingBy(PatrolIntelligentEquip::getUseMode));
            List<CodeSimpleVO> useTypeCodeList = codeService.findCodeSimpleInfoByParentType("UseType");
            Map<String, String> useTypeCodeMap = useTypeCodeList.stream().collect(Collectors.toMap(CodeSimpleVO::getKey, CodeSimpleVO::getName));
            for (Map.Entry<String, List<PatrolIntelligentEquip>> useModeEntry : useModeMap.entrySet()) {
                if (CollUtil.isNotEmpty(useModeEntry.getValue())) {
                    List<String> useModeDeviceCodeList = useModeEntry.getValue().stream().map(PatrolIntelligentEquip::getPatrolDeviceCode).collect(Collectors.toList());
                    List<MeasurePointBaseVO> useModePointList = pointList.stream().filter(p -> useModeDeviceCodeList.contains(p.getPatrolDeviceCode())).collect(Collectors.toList());
                    intelligentEquipList.add(buildIntelligentEquipVO(useTypeCodeMap.get(useModeEntry.getKey()), useModeEntry.getValue(), useModePointList, allPointList, null));
                }
            }

            // 无人机
            List<PatrolIntelligentEquip> uavEquipList = equipAllList.stream().filter(c -> StringUtils.equals(c.getDeviceType(), BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType13)).collect(Collectors.toList());
            intelligentEquipList.add(buildIntelligentEquipVO(EquipClassDict.UAV.getVal(), uavEquipList, null, allPointList, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType13));

            // 声纹
            List<PatrolIntelligentEquip> voiceEquipList = equipAllList.stream().filter(c -> StringUtils.equals(c.getDeviceType(), BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType14)).collect(Collectors.toList());
            List<String> voiceDeviceCodes = cameraEquipList.stream().map(PatrolIntelligentEquip::getPatrolDeviceCode).filter(StrUtil::isNotBlank).collect(Collectors.toList());
            List<MeasurePointBaseVO> voicePointList = measurePointService.getPointsByDeviceCodes(stationId, voiceDeviceCodes, BaseCodeConstants.CodeType_PointType.KEY_PointType01);
            intelligentEquipList.add(buildIntelligentEquipVO(EquipClassDict.VOICE.getVal(), voiceEquipList, voicePointList, allPointList, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType14));

            // 机器人
            List<String> robotTypeList = Lists.newArrayList();
            robotTypeList.add(BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType01);
            robotTypeList.add(BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType02);
            robotTypeList.add(BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType03);
            List<PatrolIntelligentEquip> robotEquipList = equipAllList.stream().filter(c -> StringUtils.isNotEmpty(c.getDeviceType()) && robotTypeList.contains(c.getDeviceType())).collect(Collectors.toList());
            intelligentEquipList.add(buildIntelligentEquipVO(EquipClassDict.ROBOT.getVal(), robotEquipList, null, allPointList, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType01));   

        }*/
        return intelligentEquipList;
    }

 /*   private IntelligentEquipVO buildIntelligentEquipVO(String useMode, List<PatrolIntelligentEquip> equipList, List<MeasurePointBaseVO> pointList, List<MeasurePointBaseVO> allPointList, String deviceType) {
        IntelligentEquipVO equipVO = new IntelligentEquipVO();
        equipVO.setUseMode(useMode);
        int allQty = equipList.size();
        equipVO.setAllQty(allQty);
        long inlineQty = equipList.stream().filter(e -> BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01.equals(e.getIsOnline())).count();
        equipVO.setInlineQty(inlineQty);
        double inlinePercent = ((double)inlineQty / allQty) * 100;
        equipVO.setInlinePercent(String.format("%.2f%%", inlinePercent));
        int type1PointQty = CollUtil.isNotEmpty(pointList) ? pointList.size() : 0;
        equipVO.setType1PointQty(type1PointQty);
        equipVO.setCoverPercent(calculateCoverPercent(type1PointQty, CollUtil.isNotEmpty(allPointList) ? allPointList.size() : 0));
        equipVO.setDeviceType(deviceType);
        return equipVO;
    }*/

    private String calculateCoverPercent(int pointQty, int allPointQty) {
        if (allPointQty == 0) {
            return "-";
        }
        double coverPercent = ((double) pointQty / allPointQty) * 100;
        return String.format("%.2f%%", coverPercent);
    }

    @Override
    public List<PatrolIntelligentEquip> findByIdList(List<String> idList) {
        return this.lambdaQuery().in(PatrolIntelligentEquip::getObjId, idList).list();
    }

    @Override
    public Integer countByAreaId(String areaId) {
        return 0;
    }

    @Override
    public Integer countByBayIds(List<String> bayIds) {
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEquipByList(List<String> objIds, String remoteIp) throws GeneralSimpleException {
        List<PatrolIntelligentEquip> intelligentEquipList = this.lambdaQuery().in(PatrolIntelligentEquip::getObjId, objIds).list();
        if (CollectionUtils.isNotEmpty(intelligentEquipList)) {
            boolean status = this.lambdaUpdate()
                    .set(PatrolIntelligentEquip::getDeleteState, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                    .set(PatrolIntelligentEquip::getUpdateTime, new Date())
                    .in(PatrolIntelligentEquip::getObjId, objIds).update();
            if (status) {
                intelligentEquipList.parallelStream().forEach(intelligentEquip -> {
                    this.intelligentEquipChannelService.lambdaUpdate().eq(PatrolIntelligentEquipChannel::getEquipId, intelligentEquip.getObjId()).remove();

                    List<String> channelCodeList = Lists.newArrayList();
                    List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                            .eq(PatrolIntelligentEquipChannel::getEquipId, intelligentEquip.getObjId()).list();
                    if(CollectionUtils.isNotEmpty(channelList)){
                        channelCodeList.addAll(channelList.stream().map(PatrolIntelligentEquipChannel::getChannelCode).collect(Collectors.toList()));
                    }
                    try {
                        //通知外网sip 服务删除设备
                        CompletableFuture.runAsync(() -> {
                            try {
                                deleteProxyMedia(intelligentEquip,channelCodeList);
                            } catch (GeneralSimpleException e) {
                                log.error("外网sip 服务删除 智能设备{}异常",intelligentEquip.getPatrolDeviceName(),e);
                            }
                        });
                        String userId = BaseCommonUtils.extractUserIdtByToken();
                        UserBaseInfoVO userBaseInfoVO = userService.findById(userId);
                        String logMsg = LogRecordUtils.delEquip(userBaseInfoVO.getUserName(), intelligentEquip.getPatrolDeviceName());
                        logService.addLogRecord(userId, userBaseInfoVO.getUserName(), BaseCodeConstants.CodeType_LogType.KEY_LogType04, logMsg, remoteIp);
                    }catch (Exception e){
                        log.error("智能设备{}删除失败", intelligentEquip.getPatrolDeviceName(), e);
                    }
                });
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteNvrByList(List<String> objIds, String remoteIp) throws GeneralSimpleException {
        List<PatrolIntelligentEquip> intelligentEquipList = this.lambdaQuery().in(PatrolIntelligentEquip::getObjId, objIds).list();
        if (CollectionUtils.isNotEmpty(intelligentEquipList)) {
            boolean status = removeByIds(objIds);
            if (status) {
                String userId = BaseCommonUtils.extractUserIdtByToken();
                UserBaseInfoVO userBaseInfoVO = userService.findById(userId);
                intelligentEquipList.parallelStream().forEach(intelligentEquip -> {
                    try {
                        intelligentEquip.setDeleteState(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                        List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                                .eq(PatrolIntelligentEquipChannel::getBelongEquipId, intelligentEquip.getObjId()).list();
                        //无 数据下发
                        //dataDistribute(intelligentEquip, channelList);
                        String logMsg = LogRecordUtils.delEquip(userBaseInfoVO.getUserName(), intelligentEquip.getPatrolDeviceName());
                        logService.addLogRecord(userId, userBaseInfoVO.getUserName(), BaseCodeConstants.CodeType_LogType.KEY_LogType04, logMsg, remoteIp);
                    } catch (Exception e) {
                        log.error("智能设备{}删除失败", intelligentEquip.getPatrolDeviceName(), e);
                    }
                });
                this.intelligentEquipChannelService.lambdaUpdate().in(PatrolIntelligentEquipChannel::getBelongEquipId, objIds)
                        .set(PatrolIntelligentEquipChannel::getBelongEquipId, null)
                        .set(PatrolIntelligentEquipChannel::getUpdateTime, new Date())
                        .set(PatrolIntelligentEquipChannel::getChannelCodeNvr, null)
                        .set(PatrolIntelligentEquipChannel::getChannelNumber, null).update();
                //删除位置信息
                //equipCoordinateService.deleteByEquipIds(objIds);
            }
        }
        return true;
    }

    @Override
    public String exportEquip(PatrolIntelligentEquipQueryDTO dto) throws Exception {
        List<PatrolIntelligentEquipExportVO> result = Lists.newArrayList();
        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();
        boolean headOffice = userService.checkHeadOffice();
        List<String> orgIdList = null;
        if(!headOffice){
            orgIdList = orgService.getDataPermissionOrgId();
        }

        //当前组织的工程列表
        List<ConstructionWorkBean> constructionWorkBeanList = this.constructionWorkService.lambdaQuery()
                .in(!headOffice, ConstructionWorkBean::getProjectDepartmentObjId, orgIdList)
                .orderByAsc(ConstructionWorkBean::getCreateTime).list();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            List<String> workObjIdList = Lists.newArrayList();
            constructionWorkBeanList.forEach(
                    constructionWorkBean -> workObjIdList.add(constructionWorkBean.getObjId())
            );
            wrapper.in(PatrolIntelligentEquip::getConstructionWorkId, workObjIdList);
        }

        //所属工程
        if (StringUtils.isNotBlank(dto.getConstructionWorkId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkId, dto.getConstructionWorkId());
        }
        //所属施工现场
        if (StringUtils.isNotBlank(dto.getConstructionWorkSiteId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkSiteId, dto.getConstructionWorkSiteId());
        }
        //模糊查询
        if (StringUtils.isNotBlank(dto.getSearchName())) {
            wrapper.and(w -> w.like(PatrolIntelligentEquip::getPatrolDeviceName, dto.getSearchName())
                    .or()
                    .like(PatrolIntelligentEquip::getPatrolDeviceCode, dto.getSearchName()));
        }
        //使用类型
        if (StringUtils.isNotBlank(dto.getUseMode())) {
            wrapper.eq(PatrolIntelligentEquip::getUseMode, dto.getUseMode());
        }
        //运行状态
        if (StringUtils.isNotBlank(dto.getRunStatus())) {
            wrapper.eq(PatrolIntelligentEquip::getRunStatus, dto.getRunStatus());
        }
        //视频类型
        if (StringUtils.isNotBlank(dto.getVideoMode())) {
            wrapper.eq(PatrolIntelligentEquip::getVideoMode, dto.getVideoMode());
        }
        wrapper.eq(PatrolIntelligentEquip::getDeviceType, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType10);
        wrapper.orderByDesc(PatrolIntelligentEquip::getCreateTime);

        List<PatrolIntelligentEquip> list = this.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            for (PatrolIntelligentEquip equip : list) {
                PatrolIntelligentEquipExportVO vo = new PatrolIntelligentEquipExportVO();
                //所属工程
                if (StringUtils.isNotBlank(equip.getConstructionWorkId())) {
                    ConstructionWorkBean constructionWorkBean = this.constructionWorkService.getById(equip.getConstructionWorkId());
                    if (Objects.nonNull(constructionWorkBean)) {
                        vo.setWorkName(constructionWorkBean.getWorkName());
                    }
                }
                //所属施工现场
                if (StringUtils.isNotBlank(equip.getConstructionWorkSiteId())) {
                    vo.setSiteName(this.constructionWorkSiteService.findNameByObjId(equip.getConstructionWorkSiteId()));
                }
                vo.setPatrolDeviceName(equip.getPatrolDeviceName());
                vo.setPatrolDeviceCode(equip.getPatrolDeviceCode());
                //品牌
                if (StringUtils.isNotBlank(equip.getBrand())) {
                    vo.setBrand(codeService.findNameByParentTypeAndKey(BaseCodeConstants.CodeType_02.KEY_BrandType, equip.getBrand()));
                }
                if (StringUtils.isNotBlank(equip.getVideoMode())) {
                    vo.setVideoMode(codeService.findNameByParentTypeAndKey(BaseCodeConstants.CodeType_02.KEY_VideoType, equip.getVideoMode()));
                }
                if (StringUtils.isNotBlank(equip.getUseMode())) {
                    vo.setUseMode(codeService.findNameByParentTypeAndKey(BaseCodeConstants.CodeType_02.KEY_UseType, equip.getUseMode()));
                }
                if (StringUtils.isNotBlank(equip.getRunStatus())) {
                    if (StringUtils.equals(equip.getRunStatus(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)) {
                        vo.setRunStatus("停运");
                    } else if (StringUtils.equals(equip.getRunStatus(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)) {
                        vo.setRunStatus("在运");
                    }
                }
                result.add(vo);
            }
        }
        XSSFWorkbook workbook = PoiTools.addDataAndMeterHeaderWithObject(result, "摄像机台账");
        String ret = System.getProperty("user.dir") + "/" + System.currentTimeMillis() + ".xlsx";
        PoiTools.write2Disk(workbook, ret);
        return ret;
    }

    @Override
    public String exportEquipVoice(PatrolIntelligentEquipVoiceQueryDTO dto) throws Exception {
       /* List<PatrolIntelligentEquipVoiceExportVO> result = Lists.newArrayList();
        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();
        //所属厂站
        if(StringUtils.isNotBlank(dto.getStationId())){
            wrapper.eq(PatrolIntelligentEquip::getStationId,dto.getStationId());
        }
        //所属区域
        if(StringUtils.isNotBlank(dto.getAreaId())){
            wrapper.eq(PatrolIntelligentEquip::getAreaId,dto.getAreaId());
        }
        //模糊查询
        if(StringUtils.isNotBlank(dto.getSearchName())){
            wrapper.and(w -> w.like(PatrolIntelligentEquip::getPatrolDeviceName,dto.getSearchName())
                    .or()
                    .like(PatrolIntelligentEquip::getPatrolDeviceCode,dto.getSearchName()));
        }
        //运行状态
        if(StringUtils.isNotBlank(dto.getRunStatus())){
            wrapper.eq(PatrolIntelligentEquip::getRunStatus,dto.getRunStatus());
        }
        //所属品牌
        if(StringUtils.isNotBlank(dto.getBrand())){
            wrapper.eq(PatrolIntelligentEquip::getBrand,dto.getBrand());
        }
        wrapper.eq(PatrolIntelligentEquip::getDeviceType,BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType14);
        wrapper.orderByDesc(PatrolIntelligentEquip::getCreateTime);

        List<PatrolIntelligentEquip> list = this.list(wrapper);
        if(CollectionUtils.isNotEmpty(list)){
            for(PatrolIntelligentEquip equip : list){
                PatrolIntelligentEquipVoiceExportVO vo = new PatrolIntelligentEquipVoiceExportVO();
                //所属厂站
                if(StringUtils.isNotBlank(equip.getStationId())){
                    StationVO stationVO = stationService.findById(equip.getStationId());
                    if(Objects.nonNull(stationVO)){
                        vo.setStationName(stationVO.getStationName());
                    }
                }
                //所属区域
                if(StringUtils.isNotBlank(equip.getAreaId())){
                    AreaBean areaBean = this.areaService.getById(equip.getAreaId());
                    if(Objects.nonNull(areaBean)){
                        vo.setAreaName(areaBean.getAreaName());
                    }
                }
                vo.setPatrolDeviceName(equip.getPatrolDeviceName());
                vo.setPatrolDeviceCode(equip.getPatrolDeviceCode());
                vo.setDeviceModel(equip.getDeviceModel());
                //生产厂家
                if(StringUtils.isNotBlank(equip.getBrand())){
                    vo.setBrand(codeService.findNameByParentTypeAndKey(BaseCodeConstants.CodeType_02.KEY_BrandType, equip.getBrand()));
                }
                vo.setPlace(equip.getPlace());
                //装置类型
                vo.setDeviceTypeName("声纹采集器");
                if(StringUtils.isNotBlank(equip.getRunStatus())) {
                    if(StringUtils.equals(equip.getRunStatus(),BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)){
                        vo.setRunStatus("停运");
                    }else if(StringUtils.equals(equip.getRunStatus(),BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)){
                        vo.setRunStatus("在运");
                    }
                }
                result.add(vo);
            }
        }
        XSSFWorkbook workbook = PoiTools.addDataAndMeterHeaderWithObject(result, "声纹采集器台账");
        String ret = System.getProperty("user.dir") + "/" +  System.currentTimeMillis() + ".xlsx";
        PoiTools.write2Disk(workbook, ret);
        return ret;*/
        return null;
    }

    @Override
    public String exportEquipNvr(PatrolIntelligentEquipNvrQueryDTO dto) throws Exception {
        List<PatrolIntelligentEquipNvrExportVO> result = Lists.newArrayList();
        LambdaQueryWrapper<PatrolIntelligentEquip> wrapper = Wrappers.lambdaQuery();

        boolean headOffice = userService.checkHeadOffice();
        List<String> orgIdList = null;
        if(!headOffice){
            orgIdList = orgService.getDataPermissionOrgId();
        }

        //当前组织的工程列表
        List<ConstructionWorkBean> constructionWorkBeanList = this.constructionWorkService.lambdaQuery()
                .in(!headOffice, ConstructionWorkBean::getProjectDepartmentObjId, orgIdList)
                .orderByAsc(ConstructionWorkBean::getCreateTime).list();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            List<String> workObjIdList = Lists.newArrayList();
            constructionWorkBeanList.stream().forEach(
                    constructionWorkBean -> {
                        workObjIdList.add(constructionWorkBean.getObjId());
                    }
            );
            wrapper.in(PatrolIntelligentEquip::getConstructionWorkId, workObjIdList);
        }

        //所属工程
        if (StringUtils.isNotBlank(dto.getConstructionWorkId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkId, dto.getConstructionWorkId());
        }
        //所属施工现场
        if (StringUtils.isNotBlank(dto.getConstructionWorkSiteId())) {
            wrapper.eq(PatrolIntelligentEquip::getConstructionWorkSiteId, dto.getConstructionWorkSiteId());
        }
        //模糊查询
        if (StringUtils.isNotBlank(dto.getSearchName())) {
            wrapper.and(w -> w.like(PatrolIntelligentEquip::getPatrolDeviceName, dto.getSearchName())
                    .or()
                    .like(PatrolIntelligentEquip::getPatrolDeviceCode, dto.getSearchName()));
        }
        //品牌
        if (StringUtils.isNotBlank(dto.getBrand())) {
            wrapper.eq(PatrolIntelligentEquip::getBrand, dto.getBrand());
        }
        //运行状态
        if (StringUtils.isNotBlank(dto.getRunStatus())) {
            wrapper.eq(PatrolIntelligentEquip::getRunStatus, dto.getRunStatus());
        }
        wrapper.eq(PatrolIntelligentEquip::getDeviceType, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType11);
        wrapper.orderByDesc(PatrolIntelligentEquip::getCreateTime);
        List<PatrolIntelligentEquip> list = this.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            for (PatrolIntelligentEquip equip : list) {
                PatrolIntelligentEquipNvrExportVO vo = new PatrolIntelligentEquipNvrExportVO();
                //所属工程
                if (StringUtils.isNotBlank(equip.getConstructionWorkId())) {
                    ConstructionWorkBean constructionWorkBean = constructionWorkService.getById(equip.getConstructionWorkId());
                    if (Objects.nonNull(constructionWorkBean)) {
                        vo.setWorkName(constructionWorkBean.getWorkName());
                    }
                }
                //所属施工现场
                if (StringUtils.isNotBlank(equip.getConstructionWorkSiteId())) {
                    vo.setSiteName(constructionWorkSiteService.findNameByObjId(equip.getConstructionWorkSiteId()));
                }
                vo.setDeviceModel(equip.getDeviceModel());
                vo.setStorage(equip.getStorage());
                //查询已接入摄像机数
                vo.setEquipNum(this.intelligentEquipChannelService.lambdaQuery().eq(PatrolIntelligentEquipChannel::getBelongEquipId, equip.getObjId()).count());
                if (StringUtils.isNotBlank(equip.getBrand())) {
                    vo.setBrand(codeService.findNameByParentTypeAndKey(BaseCodeConstants.CodeType_02.KEY_BrandType, equip.getBrand()));
                }
                if (StringUtils.isNotBlank(equip.getRunStatus())) {
                    if (StringUtils.equals(equip.getRunStatus(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)) {
                        vo.setRunStatus("停运");
                    } else if (StringUtils.equals(equip.getRunStatus(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)) {
                        vo.setRunStatus("在运");
                    }
                }
                result.add(vo);
            }
        }
        XSSFWorkbook workbook = PoiTools.addDataAndMeterHeaderWithObject(result, "硬盘录像机台账");
        String ret = System.getProperty("user.dir") + "/" + System.currentTimeMillis() + ".xlsx";
        PoiTools.write2Disk(workbook, ret);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean relateEquips(PatrolIntelligentEquipNvrRelateDTO dto) {
        //关联通道
        if (CollectionUtils.isNotEmpty(dto.getEquipRelateDTOList())) {
            //先清除原先关联的Nvr
            this.intelligentEquipChannelService.lambdaUpdate().eq(PatrolIntelligentEquipChannel::getBelongEquipId, dto.getObjId())
                    .set(PatrolIntelligentEquipChannel::getBelongEquipId, null)
                    .set(PatrolIntelligentEquipChannel::getChannelNumber, null)
                    .set(PatrolIntelligentEquipChannel::getRelateOrder, null).update();
            int order = 1;
            for (PatrolIntelligentEquipRelateDTO p : dto.getEquipRelateDTOList()) {
                this.intelligentEquipChannelService.lambdaUpdate().eq(PatrolIntelligentEquipChannel::getObjId, p.getObjId())
                        .set(PatrolIntelligentEquipChannel::getBelongEquipId, dto.getObjId())
                        .set(PatrolIntelligentEquipChannel::getChannelNumber, p.getChannelNumber())
                        .set(PatrolIntelligentEquipChannel::getChannelCodeNvr, getChannelCodeNvr(p.getChannelCode()))
                        .set(PatrolIntelligentEquipChannel::getRelateOrder, order).update();
                order++;
            }
            //数据下发
/*            PatrolIntelligentEquip equip = this.getById(dto.getObjId());
            List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                    .eq(PatrolIntelligentEquipChannel::getBelongEquipId,dto.getObjId()).list();
            dataDistribute(equip,channelList);*/
        }
        return true;
    }

    private String getChannelCodeNvr(String channelCode) {
        if (StringUtils.isNotBlank(channelCode)) {
            return channelCode.substring(0, 10) + "132" + channelCode.substring(13);
        }
        return null;
    }


//    private void listChildOrg(List<String> pidList, List<String> childOrgIdList) {
//        LambdaQueryWrapper<OrgBean> orgWrapper = Wrappers.lambdaQuery();
//        orgWrapper.in(OrgBean::getPid, pidList);
//        List<OrgBean> orgList = orgMapper.selectList(orgWrapper);
//        if (CollUtil.isNotEmpty(orgList)) {
//            List<String> childIdList = orgList.stream().map(OrgBean::getId).collect(Collectors.toList());
//            childOrgIdList.addAll(childIdList);
//            listChildOrg(childIdList, childOrgIdList);
//        }
//    }

    @Override
    public List<PatrolIntelligentEquipTreeVO> findTree(PatrolIntelligentEquipTreeDTO dto)throws GeneralSimpleException {
        List<PatrolIntelligentEquipTreeVO> equipTreeVOList = Lists.newArrayList();
        boolean headOffice = userService.checkHeadOffice();
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        if(!headOffice){
            boolean department = orgService.checkDepartment();
            if(department){
                // 项目部
                equipTreeVOList = findDepartment(dto, orgId);
            }else{
                //参建单位
                boolean generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){
                    equipTreeVOList = findGeneralContractingUnit(dto, orgId);
                }
            }
        }else{
            // 总部管理员
            equipTreeVOList = findTreeHeadOffice(dto);
        }

        return setParentOrg(headOffice, orgId, equipTreeVOList);
    }

    /**
     * 查询总部树
     * @param dto 查询条件
     * @return 树
     */
    public List<PatrolIntelligentEquipTreeVO> findTreeHeadOffice(PatrolIntelligentEquipTreeDTO dto) {
        List<PatrolIntelligentEquipTreeVO> equipTreeVOList = Lists.newArrayList();
        List<OrgBean> rootOrgBeanList = orgService.lambdaQuery()
                .isNull(OrgBean::getPid).list();
        if(CollectionUtils.isNotEmpty(rootOrgBeanList)){
            // 总公司下的项目
            rootOrgBeanList.forEach(orgBean -> {
                PatrolIntelligentEquipTreeVO treeNext = findTreeNext(dto, orgBean);
                if(Objects.nonNull(treeNext)){
                    equipTreeVOList.add(treeNext);
                }
            });
        }
        return equipTreeVOList;
    }

    /**
     * 查询项目部树
     * @param dto 查询条件
     * @return 树
     */
    public List<PatrolIntelligentEquipTreeVO> findDepartment(PatrolIntelligentEquipTreeDTO dto, String orgId) {

        //根据单位信息查询所属项目部机构
        List<PatrolIntelligentEquipTreeVO> equipTreeVOList = Lists.newArrayList();
        OrgBean departmentOrgBean = orgService.lambdaQuery()
                .eq(OrgBean::getId, orgService.findDepartmentOrgIdByOrgId(orgId))
                .one();
        if(Objects.nonNull(departmentOrgBean)){
            // 总公司下的项目
            PatrolIntelligentEquipTreeVO treeNext = findTreeNext(dto, departmentOrgBean);
            if(Objects.nonNull(treeNext)){
                equipTreeVOList.add(treeNext);
            }
        }
        return equipTreeVOList;
    }    
    
    /**
     * 查询总包单位
     * @param dto 查询条件
     * @return 树
     */
    public List<PatrolIntelligentEquipTreeVO> findGeneralContractingUnit(PatrolIntelligentEquipTreeDTO dto, String orgId) {
        List<PatrolIntelligentEquipTreeVO> equipTreeVOList = Lists.newArrayList();
        List<String> workIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId(orgId);
        if(CollectionUtils.isNotEmpty(workIdList)){
            equipTreeVOList = findWorkInfoByWorkId(workIdList, dto.getRunStatus(), dto.getIsOnline(),dto.getDeviceType(),dto.getName());
            if(CollectionUtils.isNotEmpty(equipTreeVOList)){
                OrgBean orgBean = orgService.lambdaQuery()
                        .isNull(OrgBean::getPid).last(Constants.LAST_SQL).one();

                if(Objects.nonNull(orgBean)){
                    PatrolIntelligentEquipTreeVO treeVO = new PatrolIntelligentEquipTreeVO();
                    treeVO.setObjId(orgBean.getId());
                    treeVO.setObjName(orgBean.getName());
                    treeVO.setChildrenList(equipTreeVOList);
                    treeVO.setType("001");

                    List<PatrolIntelligentEquipTreeVO> treeVOList = Lists.newArrayList();
                    treeVOList.add(treeVO);
                    return treeVOList;
                }
            }
            return equipTreeVOList;
        }else{
            return null;
        }
    }

    /**
     * 获取下级项目部和项目
     * @param dto 查询条件
     * @param orgBean 单位
     * @return 树
     */
    public PatrolIntelligentEquipTreeVO findTreeNext(PatrolIntelligentEquipTreeDTO dto, OrgBean orgBean) {
        PatrolIntelligentEquipTreeVO equipTreeVO = new PatrolIntelligentEquipTreeVO();
        if(Objects.isNull(orgBean)){
            return null;
        }
        List<PatrolIntelligentEquipTreeVO> workTreeVOList = Lists.newArrayList();
        workTreeVOList.addAll(findWorkInfoByOrgId(orgBean.getId(), dto.getRunStatus(), dto.getIsOnline(),dto.getDeviceType(),dto.getName()));

        List<OrgBean> nextOrgBeanList = orgService.lambdaQuery()
                .eq(OrgBean::getIfEngDepartment, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                .eq(OrgBean::getPid, orgBean.getId())
                .orderByAsc(OrgBean::getOrgOrder)
                .orderByAsc(OrgBean::getCreateTime)
                .orderByAsc(OrgBean::getId)
                .list();
        if(CollectionUtils.isNotEmpty(nextOrgBeanList)){
            nextOrgBeanList.forEach(nextOrgBean -> {
                PatrolIntelligentEquipTreeVO treeNext = findTreeNext(dto, nextOrgBean);
                if(Objects.nonNull(treeNext)){
                    workTreeVOList.add(treeNext);
                }
            });
        }
       
        equipTreeVO.setObjId(orgBean.getId());
        equipTreeVO.setObjName(orgBean.getName());
        equipTreeVO.setType("00");
        equipTreeVO.setChildrenList(workTreeVOList);
        
        return equipTreeVO;
    }


    /**
     * 设备树排除项目部
     * @param dto 查询条件
     * @return 排除项目部节点的工程树
     * @throws GeneralSimpleException 异常
     */
    public List<PatrolIntelligentEquipTreeVO> findTreeExcludeProjectDepartment(PatrolIntelligentEquipTreeDTO dto) throws GeneralSimpleException {
        List<PatrolIntelligentEquipTreeVO> equipTreeVOList = Lists.newArrayList();
        boolean headOffice = userService.checkHeadOffice();
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        if(!headOffice){
            boolean department = orgService.checkDepartment();
            if(department){
                // 项目部
                List<String> orgIdList = orgService.findOrgTreeIdByOrgId(orgId);
                List<String> workIdList = Lists.newArrayList();
                if(CollectionUtils.isNotEmpty(orgIdList)){
                    workIdList = constructionWorkService.findWorkIdByProjectDepartmentObjIdIn(orgIdList);
                }
                equipTreeVOList = findTreeWork(dto, workIdList);
            }else{
                //参建单位
                boolean generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){
                    List<String> workIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId();
                    equipTreeVOList = findTreeWork(dto, workIdList);
                }
            }
        }else{
            // 总部管理员
            List<String> orgIdList = orgService.findAllDepartmentId();
            List<String> workIdList = Lists.newArrayList();
            if(CollectionUtils.isNotEmpty(orgIdList)){
                workIdList = constructionWorkService.findWorkIdByProjectDepartmentObjIdIn(orgIdList);
            }
            equipTreeVOList = findTreeWork(dto, workIdList);
        }

        return setParentOrg(headOffice, orgId, equipTreeVOList);
    }

    /**
     * 查询工程树
     * @param dto 查询条件
     * @param workIdList 工程
     * @return 工程树
     */
    private List<PatrolIntelligentEquipTreeVO> findTreeWork(PatrolIntelligentEquipTreeDTO dto, List<String> workIdList){
        if(CollectionUtils.isNotEmpty(workIdList)){
            return findWorkInfoByWorkId(workIdList, dto.getRunStatus(), dto.getIsOnline(),dto.getDeviceType(),dto.getName());    
        }
        return null;
    }
    
    @Deprecated
    public List<PatrolIntelligentEquipTreeVO> findTree_bak(PatrolIntelligentEquipTreeDTO dto)throws GeneralSimpleException {
        List<PatrolIntelligentEquipTreeVO> orgIdNameList = Lists.newArrayList();
        List<OrgBean> orgBeanList= Lists.newArrayList();
        boolean headOffice = userService.checkHeadOffice();
        String orgId = BaseCommonUtils.extractOrdIdByToken();
       // List<String> orgIdList=null;
        if(!headOffice){
            //orgIdList = orgService.getDataPermissionOrgId();
            //当前用户不具备总部管理员的角色
            if(StringUtils.isBlank(orgId)){
                log.info("单位信息不存在");
                throw new GeneralSimpleException("100003");
            }

            // 是否项目部管理员,如果是项目部管理员，优先以项目部管理员权限为主
            boolean projectDepartment = userService.checkProjectDepartment();
            if(!projectDepartment){
                // 是否总包单位管理员
                boolean generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){
                    
                    List<String> workIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId();
                    if(CollectionUtils.isNotEmpty(workIdList)){
                        orgIdNameList = findWorkInfoByWorkId(workIdList, dto.getRunStatus(), dto.getIsOnline(),dto.getDeviceType(),dto.getName());
                        if(CollectionUtils.isNotEmpty(orgIdNameList)){
                            OrgBean orgBean = orgService.findRootNodeByOrgId(orgIdNameList.get(0).getObjId());

                            if(Objects.nonNull(orgBean)){
                                PatrolIntelligentEquipTreeVO treeVO = new PatrolIntelligentEquipTreeVO();
                                treeVO.setObjId(orgBean.getId());
                                treeVO.setObjName(orgBean.getName());
                                treeVO.setChildrenList(orgIdNameList);
                                treeVO.setType("001");

                                List<PatrolIntelligentEquipTreeVO> treeVOList = Lists.newArrayList();
                                treeVOList.add(treeVO);
                                return treeVOList;
                            }
                        }
                        return orgIdNameList;
                    }else{
                        return Lists.newArrayList();
                    }
                }
            }

            //根据单位信息查询所属项目部机构
            OrgBean orgBean = orgService.lambdaQuery()
                    .eq(OrgBean::getId, orgService.findDepartmentOrgIdByOrgId(orgId))
                    .one();
            if (Objects.nonNull(orgBean)) {
                if (StringUtils.isEmpty(orgBean.getPid())){
                    orgBeanList = orgService.lambdaQuery()
                            .in(OrgBean::getPid, orgBean.getId())
                            .eq(OrgBean::getIfEngDepartment, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                            .orderByAsc(OrgBean::getOrgOrder)
                            .orderByAsc(OrgBean::getCreateTime)
                            .orderByAsc(OrgBean::getId)
                            .list();
                }else {
                    orgBeanList.add(orgBean);
                }
            }
        }else {

            List<OrgBean> orgBeanList1 = orgService.lambdaQuery().isNull(OrgBean::getPid).list();
            if(CollectionUtils.isNotEmpty(orgBeanList1)){
                List<PatrolIntelligentEquipTreeVO> finalOrgIdNameList = Lists.newArrayList();
                orgBeanList1.forEach(orgBean -> finalOrgIdNameList.addAll(findWorkInfoByOrgId(orgBean.getId(), dto.getRunStatus(), dto.getIsOnline(),dto.getDeviceType(),dto.getName())));
                orgIdNameList.addAll(finalOrgIdNameList);
            }

            //查询总部下所有项目部
            orgBeanList = orgService.lambdaQuery()
                    .eq(OrgBean::getIfEngDepartment, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                    .orderByAsc(OrgBean::getOrgOrder)
                    .orderByAsc(OrgBean::getCreateTime)
                    .orderByAsc(OrgBean::getId)
                    .list();
        }
        if (CollectionUtils.isNotEmpty(orgBeanList)){
            orgIdNameList.addAll(orgBeanList.stream().map(orgBean -> {
                    PatrolIntelligentEquipTreeVO orgIdName = new PatrolIntelligentEquipTreeVO();
                    orgIdName.setObjId(orgBean.getId());
                    orgIdName.setObjName(orgBean.getName());
                    orgIdName.setType("00");

                    orgIdName.setChildrenList(findWorkInfoByOrgId(orgBean.getId(), dto.getRunStatus(), dto.getIsOnline(),dto.getDeviceType(),dto.getName()));
                    
                    return orgIdName;
                }).collect(Collectors.toList()));
        }
        
        return setParentOrg(headOffice, orgId, orgIdNameList);
    }
    
    private List<PatrolIntelligentEquipTreeVO> setParentOrg(boolean headOffice, String orgId, List<PatrolIntelligentEquipTreeVO> equipTreeVOList){
        if(CollectionUtils.isNotEmpty(equipTreeVOList)){
            OrgBean orgBean = null;
            // 补充上级单位
            if(!headOffice){
                String departmentOrgIdByOrgId = orgService.findDepartmentOrgIdByOrgId(orgId);
                orgBean = orgService.lambdaQuery().eq(OrgBean::getId, departmentOrgIdByOrgId).one();

                if(Objects.nonNull(orgBean) && StringUtils.equals(orgBean.getId(), equipTreeVOList.get(0).getObjId())){
                    // 如果是项目部成员，并且层级部分信息一样，则直接返回
                    return equipTreeVOList;
                }
            }else{
                orgBean = orgService.findRootNodeByOrgId(orgId);
            }
            if(Objects.nonNull(orgBean)){
                PatrolIntelligentEquipTreeVO treeVO = new PatrolIntelligentEquipTreeVO();
                treeVO.setObjId(orgBean.getId());
                treeVO.setObjName(orgBean.getName());
                treeVO.setChildrenList(equipTreeVOList);
                treeVO.setType("001");

                List<PatrolIntelligentEquipTreeVO> treeVOList = Lists.newArrayList();
                treeVOList.add(treeVO);
                return treeVOList;
            }
        }
        return equipTreeVOList;
    }

    private List<PatrolIntelligentEquipTreeVO> findWorkInfoByOrgId(String orgId, String runStatus, String isOnline, String deviceType,String name){
        List<PatrolIntelligentEquipTreeVO> workIdNameList = Lists.newArrayList();
        //工程
        List<ConstructionWorkBean> constructionWorkBeanList = this.constructionWorkService.lambdaQuery()
                .eq(ConstructionWorkBean::getProjectDepartmentObjId, orgId)
                .orderByAsc(ConstructionWorkBean::getCreateTime)
                .orderByAsc(ConstructionWorkBean::getObjId)
                .list();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
           
            workIdNameList = constructionWorkBeanList.stream().map(work -> {
                PatrolIntelligentEquipTreeVO workIdName = new PatrolIntelligentEquipTreeVO();
                workIdName.setObjId(work.getObjId());
                workIdName.setObjName(work.getWorkName());
                workIdName.setType("01");
                workIdName.setConstructionWorkObjId(work.getObjId());
                //施工现场
                List<ConstructionWorkSiteBean> constructionWorkSiteBeanList = this.constructionWorkSiteService.findByWorkIdIn(Collections.singletonList(work.getObjId()));
                if (CollectionUtils.isNotEmpty(constructionWorkSiteBeanList)) {
                    List<PatrolIntelligentEquipTreeVO> workSiteIdNameList;
                    workSiteIdNameList = constructionWorkSiteBeanList.stream().map(workSite -> {
                        PatrolIntelligentEquipTreeVO workSiteIdName = new PatrolIntelligentEquipTreeVO();
                        workSiteIdName.setObjId(workSite.getObjId());
                        workSiteIdName.setObjName(constructionWorkSiteService.getNewSiteName(workSite));
                        workSiteIdName.setIfGrant(workSite.getIfGrant());
                        workSiteIdName.setType("02");
                        workSiteIdName.setConstructionWorkObjId(workSite.getConstructionWorkObjId());
                        workSiteIdName.setConstructionWorkSiteObjId(workSite.getObjId());
                        //摄像机
                        workSiteIdName.setChildrenList(this.findByWorkSiteId(workSite.getObjId(), runStatus, isOnline, deviceType,name));
                        return workSiteIdName;
                    }).collect(Collectors.toList());
                    workIdName.setChildrenList(workSiteIdNameList);
                }
                return workIdName;
            }).collect(Collectors.toList());
        }
        return workIdNameList;
    }

    /**
     * 根据工程查询工程信息
     * @param workIdList 工程ID
     * @param runStatus 运行状态
     * @param isOnline 是否在线
     * @param deviceType 设备类型
     * @param name 名称
     * @return
     */
    private List<PatrolIntelligentEquipTreeVO> findWorkInfoByWorkId(List<String> workIdList, String runStatus, String isOnline, String deviceType,String name){
        List<PatrolIntelligentEquipTreeVO> workIdNameList = Lists.newArrayList();
        //工程
        List<ConstructionWorkBean> constructionWorkBeanList = this.constructionWorkService.lambdaQuery()
                .in(ConstructionWorkBean::getObjId, workIdList)
                .orderByAsc(ConstructionWorkBean::getCreateTime)
                .orderByAsc(ConstructionWorkBean::getObjId)
                .list();
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)) {
            Map<String, List<ConstructionWorkBean>> orgIdMap = constructionWorkBeanList.stream().collect(Collectors.groupingBy(ConstructionWorkBean::getProjectDepartmentObjId));
            Set<String> orgIdList = orgIdMap.keySet();
            List<OrgBean> orgBeanList = orgService.lambdaQuery()
                    .in(OrgBean::getId, orgIdList)
                    .eq(OrgBean::getIfEngDepartment, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                    .orderByAsc(OrgBean::getOrgOrder)
                    .orderByAsc(OrgBean::getCreateTime)
                    .orderByAsc(OrgBean::getId)
                    .list();
            
            if(CollectionUtils.isEmpty(orgBeanList)){
                return null;
            }

            orgBeanList.forEach(orgBean -> {
                PatrolIntelligentEquipTreeVO orgIdName = new PatrolIntelligentEquipTreeVO();
                orgIdName.setObjId(orgBean.getId());
                orgIdName.setObjName(orgBean.getName());
                orgIdName.setType("00");
                orgIdName.setChildrenList(findWorkDetail(orgIdMap.get(orgBean.getId()), runStatus, isOnline, deviceType, name));
                workIdNameList.add(orgIdName);
            });
        }
        return workIdNameList;
    }
    
    private List<PatrolIntelligentEquipTreeVO> findWorkDetail(List<ConstructionWorkBean> constructionWorkBeanList, String runStatus, String isOnline, String deviceType,String name){
        return constructionWorkBeanList.stream().map(work -> {
            PatrolIntelligentEquipTreeVO workIdName = new PatrolIntelligentEquipTreeVO();
            workIdName.setObjId(work.getObjId());
            workIdName.setObjName(work.getWorkName());
            workIdName.setType("01");
            workIdName.setConstructionWorkObjId(work.getObjId());
            //施工现场
            List<ConstructionWorkSiteBean> constructionWorkSiteBeanList = this.constructionWorkSiteService.findByWorkIdIn(Collections.singletonList(work.getObjId()));
            if (CollectionUtils.isNotEmpty(constructionWorkSiteBeanList)) {
                List<PatrolIntelligentEquipTreeVO> workSiteIdNameList;
                workSiteIdNameList = constructionWorkSiteBeanList.stream().map(workSite -> {
                    PatrolIntelligentEquipTreeVO workSiteIdName = new PatrolIntelligentEquipTreeVO();
                    workSiteIdName.setObjId(workSite.getObjId());
                    workSiteIdName.setObjName(constructionWorkSiteService.getNewSiteName(workSite));
                    workSiteIdName.setIfGrant(workSite.getIfGrant());
                    workSiteIdName.setType("02");
                    workSiteIdName.setConstructionWorkObjId(workSite.getConstructionWorkObjId());
                    workSiteIdName.setConstructionWorkSiteObjId(workSite.getObjId());
                    //摄像机
                    workSiteIdName.setChildrenList(this.findByWorkSiteId(workSite.getObjId(), runStatus, isOnline, deviceType,name));
                    return workSiteIdName;
                }).collect(Collectors.toList());
                workIdName.setChildrenList(workSiteIdNameList);
            }
            return workIdName;
        }).collect(Collectors.toList());
    }
    
    @Override
    public List<PatrolIntelligentEquipTreeVO> findWorkAndWorkSiteTree() throws GeneralSimpleException {
        List<PatrolIntelligentEquipTreeVO> list= Lists.newArrayList();
        boolean headOffice = userService.checkHeadOffice();
        boolean generalContractingUnit = false;
        List<OrgBean> orgBeanList= Lists.newArrayList();
        List<String> workIdList = Lists.newArrayList();
        if(!headOffice){
            //当前用户不具备总部管理员的角色
            String orgId = BaseCommonUtils.extractOrdIdByToken();
            if(StringUtils.isBlank(orgId)){
                log.info("单位信息不存在");
                throw new GeneralSimpleException("100003");
            }

            boolean department = orgService.checkDepartment();
            if(department){
                // 是否项目部管理员,如果是项目部管理员，优先以项目部管理员权限为主
                boolean projectDepartment = userService.checkProjectDepartment();
                List<String> orgIdList = Lists.newArrayList();
                if(projectDepartment){
                    orgIdList = orgService.findOrgTreeIdByOrgId(orgId);
                }else{
                    orgIdList.add(orgService.findDepartmentOrgIdByOrgId(orgId));
                }

                //根据单位信息查询所属项目部机构
                if (CollectionUtils.isNotEmpty(orgIdList)) {
                    orgBeanList = orgService.lambdaQuery()
                            .in(OrgBean::getId, orgIdList)
                            .eq(OrgBean::getIfEngDepartment, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                            .orderByAsc(OrgBean::getOrgOrder)
                            .orderByAsc(OrgBean::getCreateTime)
                            .orderByAsc(OrgBean::getId)
                            .list();
                }
            }else{
                // 是否总包单位管理员
                generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){

                    workIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId();
                    if(CollectionUtils.isEmpty(workIdList)){
                        return Lists.newArrayList();
                    }
                }
            }
        }else {
            //查询总部下所有项目部
            orgBeanList = orgService.lambdaQuery()
                    .eq(OrgBean::getIfEngDepartment, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                    .orderByAsc(OrgBean::getOrgOrder)
                    .orderByAsc(OrgBean::getCreateTime)
                    .orderByAsc(OrgBean::getId)
                    .list();
        }

        List<ConstructionWorkBean> constructionWorkBeanList = Lists.newArrayList();
        if(generalContractingUnit){
            if(CollectionUtils.isNotEmpty(workIdList)){
                //工程
                constructionWorkBeanList = this.constructionWorkService.lambdaQuery()
                        .in(ConstructionWorkBean::getObjId, workIdList)
                        .orderByAsc(ConstructionWorkBean::getCreateTime)
                        .orderByAsc(ConstructionWorkBean::getObjId)
                        .list();
            }
            
        }else{
            if (CollectionUtils.isNotEmpty(orgBeanList)) {
                List<String> orgIdList = orgBeanList.stream().map(OrgBean::getId).collect(Collectors.toList());
                //工程
                constructionWorkBeanList = this.constructionWorkService.lambdaQuery()
                        .in(ConstructionWorkBean::getProjectDepartmentObjId, orgIdList)
                        .orderByAsc(ConstructionWorkBean::getCreateTime)
                        .orderByAsc(ConstructionWorkBean::getObjId)
                        .list();
            }
        }
        
        if (CollectionUtils.isNotEmpty(constructionWorkBeanList)){
            List<PatrolIntelligentEquipTreeVO> workIdNameList = constructionWorkBeanList.stream().map(work -> {
                PatrolIntelligentEquipTreeVO workIdName = new PatrolIntelligentEquipTreeVO();
                workIdName.setObjId(work.getObjId());
                workIdName.setObjName(work.getWorkName());
                workIdName.setType("01");

                List<ConstructionWorkSiteBean> constructionWorkSiteBeanList = constructionWorkSiteService.findByWorkIdIn(Collections.singletonList(work.getObjId()));

                if (CollectionUtils.isNotEmpty(constructionWorkSiteBeanList)) {
                    List<PatrolIntelligentEquipTreeVO> collect = constructionWorkSiteBeanList.stream().map(workSite -> {
                        PatrolIntelligentEquipTreeVO workSiteIdName = new PatrolIntelligentEquipTreeVO();
                        workSiteIdName.setObjId(workSite.getObjId());
                        workSiteIdName.setObjName(constructionWorkSiteService.getNewSiteName(workSite));
                        workSiteIdName.setIfGrant(workSite.getIfGrant());
                        workSiteIdName.setType("02");
                        return workSiteIdName;
                    }).collect(Collectors.toList());
                    workIdName.setChildrenList(collect);
                }
                return workIdName;
            }).collect(Collectors.toList());
            list.addAll(workIdNameList);
        }
        return list;
    }

    @Override
    public PatrolIntelligentEquipVoiceTreeVO findVoiceTree(PatrolIntelligentEquipTreeDTO dto) {
       /* PatrolIntelligentEquipVoiceTreeVO vo = new PatrolIntelligentEquipVoiceTreeVO();

        StationVO stationVO = this.stationService.findById(dto.getStationId());
        if(Objects.nonNull(stationVO)){
            vo.setObjId(dto.getStationId());
            vo.setObjName(stationVO.getStationName());
            vo.setType("01");
            //区域
            List<AreaBean> areaBeanList = this.areaService.lambdaQuery().eq(AreaBean::getStationObjId,dto.getStationId())
                    .orderByAsc(AreaBean::getCreateTime).list();
            if(CollectionUtils.isNotEmpty(areaBeanList)){
                List<PatrolIntelligentEquipVoiceTreeVO> areaIdNameList = areaBeanList.stream().map(area -> {
                    PatrolIntelligentEquipVoiceTreeVO areaIdName = new PatrolIntelligentEquipVoiceTreeVO();
                    areaIdName.setObjId(area.getObjId());
                    areaIdName.setObjName(area.getAreaName());
                    areaIdName.setType("02");
                    //装置列表
                    areaIdName.setChildrenList(this.findTreeByAreaId(area.getObjId(),dto.getRunStatus(),dto.getIsOnline()));
                    return areaIdName;
                }).collect(Collectors.toList());
                vo.setChildrenList(areaIdNameList);
            }
        }
        return vo;*/
        return null;
    }

    @Override
    public Boolean callRemote(PatrolIntelligentEquipDTO dto) throws GeneralSimpleException {
      /*  AtomicReference<Boolean> dataStatus = new AtomicReference<>(Boolean.FALSE);

        log.info("发送数据同步数据报");
        PatrolHost recPatrolHost = new PatrolHost();
        recPatrolHost.setSendCode(Constants.SEND_CODE);
        recPatrolHost.setReceiveCode(Constants.RECEIVE_CODE);
        recPatrolHost.setType(Constants.XmlType._XML_TYPE_MODEL_61);
        recPatrolHost.setCode("200");
        recPatrolHost.setCommand(Constants.XmlCommand._XML_COMMAND_3);
        FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd");
        FastDateFormat formatDate = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
        recPatrolHost.setTime(formatDate.format(new Date()));
        //主体数据
        HashMap<String,String> hashMap = new HashMap<>();
        for(Field field : dto.getClass().getDeclaredFields()){
            Object fieldValue = CommonUtils.getFieldValueByName(dto,field.getName());
            if(Objects.nonNull(fieldValue)) {
                hashMap.put(field.getName(),fieldValue.toString());
            }
        }
        if(CollectionUtils.isNotEmpty(dto.getChannelDTOList())){
            hashMap.put("channelList", JSON.toJSONString(dto.getChannelDTOList()));
        }
        //处理时间
        if(Objects.nonNull(dto.getRunTime())){
            hashMap.put("runTime",format.format(dto.getRunTime()));
        }
        if(Objects.nonNull(dto.getOutageTime())){
            hashMap.put("outageTime",format.format(dto.getOutageTime()));
        }
        recPatrolHost.setItems(Collections.singletonList(hashMap));
        String xml = CommonUtils.patrolHostToXml(recPatrolHost);
        int xmlLength = 0;
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(xml)){
            xmlLength = xml.getBytes().length;
        }
        ByteBuffer buf = ByteBuffer.allocate(25 + xmlLength);
        //封包头
        buf.put(CryptCollections.getBytes(Constants.PROTOCOL_SYNC_MARK,false));
        //发送会话序列号
        buf.put(CryptCollections.getBytes(Long.parseLong("1"), false));
        //接收会话序列号
        buf.put(CryptCollections.getBytes(Long.parseLong("1"),false));
        //会话源标识
        buf.put(CryptCollections.getBytes((short)0, false)[0]);

        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(xml)){
            //xml 的字节长度
            buf.put(CryptCollections.getBytes(xml.getBytes().length,false));
            //xml内容
            buf.put(xml.getBytes());
        }
        //结束
        buf.put(CryptCollections.getBytes(Constants.PROTOCOL_SYNC_MARK, false));

        buf.flip();
        byte[] allData = new byte[buf.limit()];
        buf.get(allData);
        buf.clear();

        Channel channel = TcpChannels.getClientChannel(Constants.RECEIVE_CODE);
        if(Objects.nonNull(channel)) {

            CallRemote.call(channel, allData, result -> {
                if (Objects.isNull(result)) {
                    return Boolean.FALSE;
                }
                //解析成功标记
                String xmlContent = new String(Arrays.copyOfRange(result, 23, result.length-2), StandardCharsets.UTF_8);
                //解析xml内容
                PatrolHost patrolHost = CommonUtils.xmlToPatrolHost(xmlContent);
                if (Objects.nonNull(patrolHost) && StringUtils.isNotBlank(patrolHost.getCode())){
                    if(StringUtils.equals(patrolHost.getCode(),Constants.XmlCode._XML_CODE_200)){
                        dataStatus.set(Boolean.TRUE);
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            });
        }
        return dataStatus.get();*/
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean callSysList(List<String> objIds) {
        List<PatrolIntelligentEquip> list = this.lambdaQuery().in(PatrolIntelligentEquip::getObjId, objIds).list();
        if (CollectionUtils.isNotEmpty(list)) {
            CompletableFuture.runAsync(() -> {
                for (PatrolIntelligentEquip equip : list) {
                    List<PatrolIntelligentEquipChannel> channels = Lists.newArrayList();
                    //如果是摄像机查询通道列表
                    if (StringUtils.equals(equip.getDeviceType(), BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType10)) {
                        channels = this.intelligentEquipChannelService.lambdaQuery()
                                .eq(PatrolIntelligentEquipChannel::getEquipId, equip.getObjId()).list();
                    }

                    //数据下发
                    dataDistributeNotSync(equip, channels);
                }
            });
        }
        return true;
    }

    @Override
    public String findIdByPatrolDeviceCode(String stationId, String patrolDeviceCode) {

      /*  List<PatrolIntelligentEquip> list = this.lambdaQuery()
                .eq(PatrolIntelligentEquip::getPatrolDeviceCode, patrolDeviceCode)
                .eq(PatrolIntelligentEquip::getStationId, stationId)
                .list();
        if(CollectionUtils.isNotEmpty(list)){
            return list.get(0).getObjId();
        }
*/
        return null;

    }

    /**
     * 根据智能设备编码查询摄像机信息
     *
     * @param patrolDeviceCode 智能设备编码
     * @return 摄像机信息
     */
    @Override
    public PatrolIntelligentEquipSimpleVO findByPatrolDeviceCode(String patrolDeviceCode) {
      /*  if(StringUtils.isEmpty(patrolDeviceCode)){
            return null;
        }
        PatrolIntelligentEquip patrolIntelligentEquip = this.lambdaQuery().eq(PatrolIntelligentEquip::getPatrolDeviceCode, patrolDeviceCode).last(Constants.LAST_SQL).one();
        if (patrolIntelligentEquip != null) {
            PatrolIntelligentEquipSimpleVO equipSimpleVO = new PatrolIntelligentEquipSimpleVO();
            equipSimpleVO.setObjId(patrolIntelligentEquip.getObjId());
            equipSimpleVO.setPatrolDeviceName(patrolIntelligentEquip.getPatrolDeviceName());
            equipSimpleVO.setPatrolDeviceCode(patrolIntelligentEquip.getPatrolDeviceCode());
            equipSimpleVO.setVideoMode(patrolIntelligentEquip.getVideoMode());
            equipSimpleVO.setBayId(patrolIntelligentEquip.getBayId());
            equipSimpleVO.setStationId(patrolIntelligentEquip.getStationId());
            equipSimpleVO.setAreaId(patrolIntelligentEquip.getAreaId());
            equipSimpleVO.setUseMode(patrolIntelligentEquip.getUseMode());
            equipSimpleVO.setPlace(patrolIntelligentEquip.getPlace());
            return equipSimpleVO;
        }*/
        return null;
    }

    /**
     * 根据所属区域或者摄像机名称查询摄像机列表
     *
     * @param dto 查询条件
     * @return 摄像机列表
     */
    @Override
    public List<PatrolIntelligentEquipListVO> findIntelligentEquipListByArea(PatrolIntelligentEquipListDTO dto) {
     /*   if(StringUtils.isEmpty(dto.getAreaId()) && StringUtils.isEmpty(dto.getDeviceName())){
            return Lists.newArrayList();
        }
        
        List<PatrolIntelligentEquipListVO> equipListVOList = Lists.newArrayList();
        List<PatrolIntelligentEquip> intelligentEquipList = null;
        if(StringUtils.isNotEmpty(dto.getDeviceName()) || StringUtils.isNotEmpty(dto.getAreaId())){
            intelligentEquipList = this.lambdaQuery()
                    .eq(PatrolIntelligentEquip::getDeviceType, BaseCodeConstants.CodeType_VideoDeviceType.KEY_VideoDeviceType10)
                    .eq(PatrolIntelligentEquip::getRunStatus, BaseCodeConstants.CodeType_RunStatus.KEY_RunStatus02)
                    .eq(PatrolIntelligentEquip::getIsOnline, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)
                    .eq(PatrolIntelligentEquip::getDeleteState, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                    .eq(StringUtils.isNotEmpty(dto.getStationId()), PatrolIntelligentEquip::getStationId, dto.getStationId())
                    .eq(StringUtils.isEmpty(dto.getDeviceName()), PatrolIntelligentEquip::getAreaId, dto.getAreaId())
                    .like(StringUtils.isNotEmpty(dto.getDeviceName()), PatrolIntelligentEquip::getPatrolDeviceName, dto.getDeviceName())
                    .orderByAsc(PatrolIntelligentEquip::getCreateTime).orderByAsc(PatrolIntelligentEquip::getObjId)
                    .list();
        }
        
        // 如果是按区域查询，并且点位关联的是区域之外的摄像机，则返回对应的摄像机信息
        if(StringUtils.isNotBlank(dto.getMeasurePointId())){
            // 如果区域ID和点位ID都不为空，则此次查询的是点位所在区域的摄像机，此时需要补充点位本身关联的摄像机，这个摄像机可能是其它区域的
            MeasurePointBean measurePointBean = measurePointService.lambdaQuery().eq(MeasurePointBean::getObjId, dto.getMeasurePointId()).one();
            if(Objects.nonNull(measurePointBean) && StringUtils.isNotBlank(measurePointBean.getPatrolDeviceCode())){

                List<String> equipIdList = Lists.newArrayList();
                if(CollectionUtils.isNotEmpty(intelligentEquipList)) {
                    equipIdList = intelligentEquipList.stream().map(PatrolIntelligentEquip::getObjId).collect(Collectors.toList());
                }
                
                List<PatrolIntelligentEquip> tempIntelligentEquipList = this.lambdaQuery()
                        .eq(PatrolIntelligentEquip::getPatrolDeviceCode, measurePointBean.getPatrolDeviceCode())
                        .eq(StringUtils.isNotEmpty(dto.getStationId()), PatrolIntelligentEquip::getStationId, dto.getStationId())
                        .notIn(CollectionUtils.isNotEmpty(equipIdList), PatrolIntelligentEquip::getObjId, equipIdList)
                        .list();
                if(CollectionUtils.isNotEmpty(tempIntelligentEquipList)){
                    intelligentEquipList.addAll(tempIntelligentEquipList);
                }
            }
        }
        
        if(CollectionUtils.isNotEmpty(intelligentEquipList)){

            List<String> equipIdList = intelligentEquipList.stream().map(PatrolIntelligentEquip::getObjId).collect(Collectors.toList());

            List<EquipCoordinateVO> equipCoordinateVOList = equipCoordinateService.findEquipsCoordinateByEquipIds(equipIdList);
            Map<String, EquipCoordinateVO> equipCoordinateMap = Maps.newHashMap();
            if(CollectionUtils.isNotEmpty(equipCoordinateVOList)){
                equipCoordinateMap = equipCoordinateVOList.stream().collect(Collectors.toMap(EquipCoordinateVO::getEquipId, Function.identity()));
            }

            Map<String, EquipCoordinateVO> finalEquipCoordinateMap = equipCoordinateMap;
            intelligentEquipList.forEach(intelligentEquip -> {
               
                List<PatrolIntelligentEquipChannel> equipChannelList = intelligentEquipChannelService.lambdaQuery()
                        .eq(PatrolIntelligentEquipChannel::getEquipId, intelligentEquip.getObjId())
                        .orderByAsc(PatrolIntelligentEquipChannel::getEquipChannelNumber)
                        .orderByAsc(PatrolIntelligentEquipChannel::getObjId)
                        .list();
                // 有多外视频流的摄像机，需要显示多条数据，显示格式为 “{摄像机名}: {视频流编号}-{视频流类型}
                if(CollectionUtils.isNotEmpty(equipChannelList)){
                    if(equipChannelList.size() == 1){
                        PatrolIntelligentEquipChannel equipChannel = equipChannelList.get(0);
                        PatrolIntelligentEquipListVO listVO = new PatrolIntelligentEquipListVO();
                        BeanUtils.copyProperties(intelligentEquip, listVO);
                        BeanUtils.copyProperties(equipChannel, listVO);
                        listVO.setEquipId(intelligentEquip.getObjId());
                        listVO.setChannelId(equipChannel.getObjId());
                        listVO.setIfMultiChannel(false);
                        listVO.setChannelCode(equipChannel.getChannelCode());
                        
                        if(finalEquipCoordinateMap.containsKey(intelligentEquip.getObjId())){
                            EquipCoordinateVO equipCoordinateVO = finalEquipCoordinateMap.get(intelligentEquip.getObjId());
                            if(Objects.nonNull(equipCoordinateVO)){
                                listVO.setLocateMode(equipCoordinateVO.getLocateMode());
                                listVO.setEquipCoordinate(equipCoordinateVO.getEquipCoordinate());
                            }
                        }
                        
                        equipListVOList.add(listVO);
                    }else{
                        for (PatrolIntelligentEquipChannel equipChannel : equipChannelList) {
                            PatrolIntelligentEquipListVO listVO = new PatrolIntelligentEquipListVO();
                            BeanUtils.copyProperties(intelligentEquip, listVO);
                            BeanUtils.copyProperties(equipChannel, listVO);
                            listVO.setEquipId(intelligentEquip.getObjId());
                            listVO.setChannelId(equipChannel.getObjId());
                            listVO.setIfMultiChannel(true);
                            listVO.setChannelCode(equipChannel.getChannelCode());
                            
                            if(finalEquipCoordinateMap.containsKey(intelligentEquip.getObjId())){
                                EquipCoordinateVO equipCoordinateVO = finalEquipCoordinateMap.get(intelligentEquip.getObjId());
                                if(Objects.nonNull(equipCoordinateVO)){
                                    listVO.setLocateMode(equipCoordinateVO.getLocateMode());
                                    listVO.setEquipCoordinate(equipCoordinateVO.getEquipCoordinate());
                                }
                            }
                            equipListVOList.add(listVO);
                        }
                    }
                }else{
                    PatrolIntelligentEquipListVO listVO = new PatrolIntelligentEquipListVO();
                    listVO.setEquipId(intelligentEquip.getObjId());
                    listVO.setPatrolDeviceName(intelligentEquip.getPatrolDeviceName());
                    listVO.setPatrolDeviceCode(intelligentEquip.getPatrolDeviceCode());
                    listVO.setUseMode(intelligentEquip.getUseMode());
                    listVO.setIsOnline(intelligentEquip.getIsOnline());

                    if(finalEquipCoordinateMap.containsKey(intelligentEquip.getObjId())){
                        EquipCoordinateVO equipCoordinateVO = finalEquipCoordinateMap.get(intelligentEquip.getObjId());
                        if(Objects.nonNull(equipCoordinateVO)){
                            listVO.setLocateMode(equipCoordinateVO.getLocateMode());
                            listVO.setEquipCoordinate(equipCoordinateVO.getEquipCoordinate());
                        }
                    }
                    equipListVOList.add(listVO);
                }
            });
        }

        return equipListVOList;*/
        return null;
    }

    /**
     * 根据点位ID查询摄像机列表
     *
     * @param measurePointId 点位ID
     * @return 摄像机列表
     */
    @Override
    public PatrolIntelligentEquipListVO findIntelligentEquipListByPointId(String stationId, String measurePointId) {
       /* MeasurePointBaseVO measurePointVO = measurePointService.findByDeviceId(measurePointId);
        if (measurePointVO == null) {
            return null;
        }
        //点位关联通道信息
        PatrolIntelligentEquipChannel equipChannel = null;
        if (StrUtil.isNotBlank(measurePointVO.getChannelId())) {
            equipChannel = intelligentEquipChannelService.getById(measurePointVO.getChannelId());
        }
        //点位关联摄像机信息
        PatrolIntelligentEquip intelligentEquip = this.lambdaQuery()
                .eq(PatrolIntelligentEquip::getPatrolDeviceCode, measurePointVO.getPatrolDeviceCode())
                .eq(PatrolIntelligentEquip::getStationId, stationId)
                .one();
        if (intelligentEquip == null) {
            return null;
        }
        PatrolIntelligentEquipListVO listVO = new PatrolIntelligentEquipListVO();
        if (equipChannel == null) {
            listVO.setEquipId(intelligentEquip.getObjId());
            listVO.setPatrolDeviceName(intelligentEquip.getPatrolDeviceName());
            listVO.setPatrolDeviceCode(intelligentEquip.getPatrolDeviceCode());
            listVO.setUseMode(intelligentEquip.getUseMode());
            listVO.setIsOnline(intelligentEquip.getIsOnline());
        } else {
            BeanUtils.copyProperties(intelligentEquip, listVO);
            BeanUtils.copyProperties(equipChannel, listVO);
            listVO.setEquipId(intelligentEquip.getObjId());
            listVO.setChannelId(equipChannel.getObjId());
        }
        //摄像机位置信息
        List<EquipCoordinateVO> equipCoordinateList = equipCoordinateService.findEquipsCoordinateByEquipIds(Arrays.asList(intelligentEquip.getObjId()));
        if (CollectionUtils.isNotEmpty(equipCoordinateList)) {
            EquipCoordinateVO equipCoordinateVO = equipCoordinateList.get(0);
            listVO.setLocateMode(equipCoordinateVO.getLocateMode());
            listVO.setEquipCoordinate(equipCoordinateVO.getEquipCoordinate());
        }
        return listVO;*/
        return null;
    }

    @Override
    public List<PatrolIntelligentEquipChannelNvrVO> findByNvrId(String belongEquipId) {
        List<PatrolIntelligentEquipChannelNvrVO> result = Lists.newArrayList();

        List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                .eq(PatrolIntelligentEquipChannel::getBelongEquipId, belongEquipId)
                .orderByAsc(PatrolIntelligentEquipChannel::getRelateOrder).list();
        if (CollectionUtils.isNotEmpty(channelList)) {
            result = channelList.stream().map(item -> {
                PatrolIntelligentEquipChannelNvrVO vo = new PatrolIntelligentEquipChannelNvrVO();
                BeanUtil.copyProperties(item, vo);
                //查询设备
                PatrolIntelligentEquipVO equipVO = this.findById(item.getEquipId());
                if (Objects.nonNull(equipVO)) {
                    vo.setPatrolDeviceName(equipVO.getPatrolDeviceName());
                    vo.setPatrolDeviceCode(equipVO.getPatrolDeviceCode());
                    vo.setUseMode(equipVO.getUseMode());
                }
                return vo;
            }).collect(Collectors.toList());
        }
        return result;
    }

    /**
     * 根据设备ID查询一个通道号
     *
     * @param equipId 设备ID
     * @return 通道号
     */
    @Override
    public PatrolIntelligentEquipChannelSimpleVO findOneChannelNumberById(String equipId) {
        List<PatrolIntelligentEquipChannel> equipChannelList = intelligentEquipChannelService.lambdaQuery().eq(PatrolIntelligentEquipChannel::getEquipId, equipId).list();
        if (CollectionUtils.isNotEmpty(equipChannelList)) {
            PatrolIntelligentEquipChannelSimpleVO channelSimpleVO = new PatrolIntelligentEquipChannelSimpleVO();
            PatrolIntelligentEquipChannel patrolIntelligentEquipChannel = equipChannelList.get(0);
            channelSimpleVO.setObjId(patrolIntelligentEquipChannel.getObjId());
            channelSimpleVO.setChannelNumber(patrolIntelligentEquipChannel.getEquipChannelNumber());
            channelSimpleVO.setSubUrl(patrolIntelligentEquipChannel.getSubUrl());
            channelSimpleVO.setMainUrl(patrolIntelligentEquipChannel.getMainUrl());
            channelSimpleVO.setUrlType(patrolIntelligentEquipChannel.getUrlType());
            channelSimpleVO.setBelongEquipId(patrolIntelligentEquipChannel.getBelongEquipId());
            return channelSimpleVO;
        }

        return null;
    }

    /**
     * 根据设备编码，查询设备信息
     *
     * @param patrolDeviceCodeList 设备编码
     * @return
     */
    public List<PatrolIntelligentEquipSimpleVO> findByPatrolDeviceCodeIn(List<String> patrolDeviceCodeList) {
        List<PatrolIntelligentEquipSimpleVO> intelligentEquipList = Lists.newArrayList();
       /* List<PatrolIntelligentEquip> patrolIntelligentEquipList =
                this.lambdaQuery().in(PatrolIntelligentEquip::getPatrolDeviceCode, patrolDeviceCodeList)
                        .list();
        
        if(CollectionUtils.isNotEmpty(patrolIntelligentEquipList)){
            patrolIntelligentEquipList.forEach(patrolIntelligentEquip -> {
                PatrolIntelligentEquipSimpleVO equipSimpleVO = new PatrolIntelligentEquipSimpleVO();
                equipSimpleVO.setObjId(patrolIntelligentEquip.getObjId());
                equipSimpleVO.setPatrolDeviceName(patrolIntelligentEquip.getPatrolDeviceName());
                equipSimpleVO.setPatrolDeviceCode(patrolIntelligentEquip.getPatrolDeviceCode());
                equipSimpleVO.setVideoMode(patrolIntelligentEquip.getVideoMode());
                equipSimpleVO.setBayId(patrolIntelligentEquip.getBayId());
                equipSimpleVO.setStationId(patrolIntelligentEquip.getStationId());
                equipSimpleVO.setAreaId(patrolIntelligentEquip.getAreaId());
                equipSimpleVO.setUseMode(patrolIntelligentEquip.getUseMode());

                List<PatrolIntelligentEquipChannel> equipChannelList = intelligentEquipChannelService.lambdaQuery().eq(PatrolIntelligentEquipChannel::getEquipId, patrolIntelligentEquip.getObjId()).list();
                
                if(CollectionUtils.isNotEmpty(equipChannelList)){
                    List<PatrolIntelligentEquipChannelSimpleVO> channelVOList = Lists.newArrayList();
                    equipChannelList.forEach(equipChannel -> {
                        PatrolIntelligentEquipChannelSimpleVO channelSimpleVO = new PatrolIntelligentEquipChannelSimpleVO();
                        channelSimpleVO.setChannelNumber(equipChannel.getChannelNumber());
                        channelSimpleVO.setEquipChannelNumber(equipChannel.getEquipChannelNumber());
                        channelSimpleVO.setObjId(equipChannel.getObjId());
                        channelSimpleVO.setUrlType(equipChannel.getUrlType());
                        channelSimpleVO.setSubUrl(equipChannel.getSubUrl());
                        channelSimpleVO.setMainUrl(equipChannel.getMainUrl());
                        channelSimpleVO.setBelongEquipId(equipChannel.getBelongEquipId());
                        channelSimpleVO.setUseMode(patrolIntelligentEquip.getUseMode());
                        channelSimpleVO.setChannelCode(equipChannel.getChannelCode());
                        channelVOList.add(channelSimpleVO);
                    });
                    equipSimpleVO.setChannelVOList(channelVOList);
                }
                intelligentEquipList.add(equipSimpleVO);
            });
        }*/
        return intelligentEquipList;
    }


    @Override
    public List<PatrolIntelligentEquipSimpleVO> findByPatrolIdIn(String patrolId) {
        List<PatrolIntelligentEquipSimpleVO> intelligentEquipList = Lists.newArrayList();
        List<PatrolIntelligentEquip> patrolIntelligentEquipList =
                this.lambdaQuery().eq(PatrolIntelligentEquip::getObjId, patrolId)
                        .list();

        if(CollectionUtils.isNotEmpty(patrolIntelligentEquipList)){
            patrolIntelligentEquipList.forEach(patrolIntelligentEquip -> {
                PatrolIntelligentEquipSimpleVO equipSimpleVO = new PatrolIntelligentEquipSimpleVO();
                equipSimpleVO.setObjId(patrolIntelligentEquip.getObjId());
                equipSimpleVO.setPatrolDeviceName(patrolIntelligentEquip.getPatrolDeviceName());
                equipSimpleVO.setPatrolDeviceCode(patrolIntelligentEquip.getPatrolDeviceCode());
                equipSimpleVO.setVideoMode(patrolIntelligentEquip.getVideoMode());
                equipSimpleVO.setConstructionWorkId(patrolIntelligentEquip.getConstructionWorkId());
                equipSimpleVO.setConstructionWorkSiteId(patrolIntelligentEquip.getConstructionWorkSiteId());
                equipSimpleVO.setUseMode(patrolIntelligentEquip.getUseMode());

                List<PatrolIntelligentEquipChannel> equipChannelList = intelligentEquipChannelService.lambdaQuery().eq(PatrolIntelligentEquipChannel::getEquipId, patrolIntelligentEquip.getObjId()).list();

                if(CollectionUtils.isNotEmpty(equipChannelList)){
                    List<PatrolIntelligentEquipChannelSimpleVO> channelVOList = Lists.newArrayList();
                    equipChannelList.forEach(equipChannel -> {
                        PatrolIntelligentEquipChannelSimpleVO channelSimpleVO = new PatrolIntelligentEquipChannelSimpleVO();
                        channelSimpleVO.setChannelNumber(equipChannel.getChannelNumber());
                        channelSimpleVO.setEquipChannelNumber(equipChannel.getEquipChannelNumber());
                        channelSimpleVO.setObjId(equipChannel.getObjId());
                        channelSimpleVO.setUrlType(equipChannel.getUrlType());
                        channelSimpleVO.setSubUrl(equipChannel.getSubUrl());
                        channelSimpleVO.setMainUrl(equipChannel.getMainUrl());
                        channelSimpleVO.setBelongEquipId(equipChannel.getBelongEquipId());
                        channelSimpleVO.setUseMode(patrolIntelligentEquip.getUseMode());
                        channelSimpleVO.setChannelCode(equipChannel.getChannelCode());
                        channelVOList.add(channelSimpleVO);
                    });
                    equipSimpleVO.setChannelVOList(channelVOList);
                }
                intelligentEquipList.add(equipSimpleVO);
            });
        }
        return intelligentEquipList;
    }


    /**
     * 根据设备编码类型查询设备信息
     *
     * @param patrolDeviceCodeList 设备编码
     * @return
     */
    public List<PatrolIntelligentEquipSimpleVO> findByTypeAndPatrolDeviceCodeList(List<String> patrolDeviceCodeList, String deviceType) {
        List<PatrolIntelligentEquipSimpleVO> intelligentEquipList = Lists.newArrayList();
     /*   List<PatrolIntelligentEquip> patrolIntelligentEquipList =
                this.lambdaQuery().in(PatrolIntelligentEquip::getPatrolDeviceCode, patrolDeviceCodeList)
                        .eq(PatrolIntelligentEquip::getDeviceType, deviceType)
                        .list();
        if(CollectionUtils.isNotEmpty(patrolIntelligentEquipList)){
            patrolIntelligentEquipList.forEach(patrolIntelligentEquip -> {
                PatrolIntelligentEquipSimpleVO equipSimpleVO = new PatrolIntelligentEquipSimpleVO();
                equipSimpleVO.setObjId(patrolIntelligentEquip.getObjId());
                equipSimpleVO.setPatrolDeviceName(patrolIntelligentEquip.getPatrolDeviceName());
                equipSimpleVO.setPatrolDeviceCode(patrolIntelligentEquip.getPatrolDeviceCode());
                equipSimpleVO.setStationId(patrolIntelligentEquip.getStationId());
                equipSimpleVO.setProductCode(patrolIntelligentEquip.getProductCode());
                intelligentEquipList.add(equipSimpleVO);
            });
        }*/
        return intelligentEquipList;
    }

    @Override
    public IPage<PatrolIntelligentEquipChannelNvrVO> findNoRelatePage(PatrolIntelligentEquipChannelNvrDTO dto)throws GeneralSimpleException {
        return this.intelligentEquipChannelService.findPage(dto);
    }

    public void findInfo(PatrolIntelligentEquipVO vo) {

        //所属工程
        if (StringUtils.isNotBlank(vo.getConstructionWorkId())) {
            ConstructionWorkBean constructionWorkBean = constructionWorkService.getById(vo.getConstructionWorkId());
            if (Objects.nonNull(constructionWorkBean)) {
                vo.setConstructionWorkName(constructionWorkBean.getWorkName());
            }
        }

        //所属施工现场
        if (StringUtils.isNotBlank(vo.getConstructionWorkSiteId())) {
            vo.setConstructionWorkSiteName(constructionWorkSiteService.findNameByObjId(vo.getConstructionWorkSiteId()));
            ConstructionWorkSiteBean constructionWorkSiteBean = constructionWorkSiteService.getById(vo.getConstructionWorkSiteId());
            if (Objects.nonNull(constructionWorkSiteBean)) {
                vo.setIfGrant(constructionWorkSiteBean.getIfGrant());
            }
        }

        //查询通道列表
        List<PatrolIntelligentEquipChannel> channelList = this.intelligentEquipChannelService.lambdaQuery()
                .eq(PatrolIntelligentEquipChannel::getEquipId, vo.getObjId())
                .orderByAsc(PatrolIntelligentEquipChannel::getEquipChannelNumber).list();
        if (CollectionUtils.isNotEmpty(channelList)) {
            vo.setChannelVOList(channelList.stream().map(item -> {
                PatrolIntelligentEquipChannelVO channelVO = new PatrolIntelligentEquipChannelVO();
                BeanUtil.copyProperties(item, channelVO);
                if (StringUtils.isNotBlank(channelVO.getBelongEquipId())) {
                    PatrolIntelligentEquipNvrVO nvrVO = this.findNvrById(channelVO.getBelongEquipId());
                    if (Objects.nonNull(nvrVO) && StringUtils.isNotBlank(nvrVO.getPatrolDeviceCode())) {
                        channelVO.setBelongEquipCode(nvrVO.getPatrolDeviceCode());
                    }
                }
                return channelVO;
            }).collect(Collectors.toList()));
        }
    }

    /**
     * 向外网sip服务添加设备
     */
    @Override
    public void addInternetProxyMedia(PatrolIntelligentEquip equip, List<String> channelCodeList) throws GeneralSimpleException {
        AddDeviceDTO deviceDTO = new AddDeviceDTO();
        deviceDTO.setProxySipCode(intranetProxySipCode);
        deviceDTO.setSipCode(equip.getSipCode());
        deviceDTO.setChannelCodeList(channelCodeList);
        String url = internalNetWorkSipServerAddress + ":" + internalNetWorkSipServerPort + "/api/notify/proxyMediaServer/add";
        String result = CommonUtils.sendPost(url, JSON.toJSONString(deviceDTO));
        if(StringUtils.isNotBlank(result)){
            WVPResult wvpResult = JSON.parseObject(result,WVPResult.class);
            if(Objects.nonNull(wvpResult) && !StringUtils.equals(wvpResult.getCode(), Constants.SipResultCode.SUCCESS_CODE)){
                log.error("外网视频代理添加设备失败：{}",wvpResult.getMsg());
                throw new GeneralSimpleException("600203");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProxyMedia(String oldAgreement,PatrolIntelligentEquip equip,List<String> channelCodeList) throws GeneralSimpleException {
        UpdateDeviceDTO deviceDTO = new UpdateDeviceDTO();
        deviceDTO.setProxySipCode(intranetProxySipCode);
        deviceDTO.setSipCode(equip.getSipCode());
        deviceDTO.setChannelCodeList(channelCodeList);
        deviceDTO.setOriginAccessProtocol(oldAgreement);
        deviceDTO.setCurrentAccessProtocol(equip.getAgreement());
        String url = internalNetWorkSipServerAddress + ":" + internalNetWorkSipServerPort + "/api/notify/proxyMediaServer/updateDeviceAccessProtocol";
        String result = CommonUtils.sendPost(url,JSON.toJSONString(deviceDTO));
        if(StringUtils.isNotBlank(result)){
            WVPResult wvpResult = JSON.parseObject(result,WVPResult.class);
            if(Objects.nonNull(wvpResult) && !StringUtils.equals(wvpResult.getCode(), Constants.SipResultCode.SUCCESS_CODE)){
                log.error("修改设备接入协议失败：{}",wvpResult.getMsg());
                throw new GeneralSimpleException("600207");
            }
        }
    }

    /**
     * 根据施工现场id/摄像机id获取所属工程及现场信息
     * @param dto 施工现场id/摄像机id
     * @return 所属工程及现场信息
     */
    @Override
    public ConstructionWorkAndWorkSiteInfoVO findWorkAndWorkSiteInfoByWorksiteIdOrEquipObjId(ConstructionWorkSiteIdOrEquipObjIdDTO dto) {
        ConstructionWorkAndWorkSiteInfoVO constructionWorkAndWorkSiteInfoVO=null;
        if (StringUtils.isNotEmpty(dto.getConstructionWorkSiteObjId())){
            ConstructionWorkSiteBean constructionWorkSiteBean = constructionWorkSiteService.getById(dto.getConstructionWorkSiteObjId());
            if(Objects.nonNull(constructionWorkSiteBean)){
                constructionWorkAndWorkSiteInfoVO = new ConstructionWorkAndWorkSiteInfoVO();
                constructionWorkAndWorkSiteInfoVO.setConstructionWorkSiteObjId(dto.getConstructionWorkSiteObjId());
                constructionWorkAndWorkSiteInfoVO.setConstructionWorkObjId(constructionWorkSiteBean.getConstructionWorkObjId());
                constructionWorkAndWorkSiteInfoVO.setIfGrant(constructionWorkSiteBean.getIfGrant());
            }
        }

        if (StringUtils.isNotEmpty(dto.getObjId())){
            PatrolIntelligentEquip patrolIntelligentEquip = this.getById(dto.getObjId());
            if(Objects.nonNull(patrolIntelligentEquip)){
                constructionWorkAndWorkSiteInfoVO = new ConstructionWorkAndWorkSiteInfoVO();
                constructionWorkAndWorkSiteInfoVO.setConstructionWorkObjId(patrolIntelligentEquip.getConstructionWorkId());
                constructionWorkAndWorkSiteInfoVO.setConstructionWorkSiteObjId(patrolIntelligentEquip.getConstructionWorkSiteId());
                ConstructionWorkSiteBean constructionWorkSiteBean = constructionWorkSiteService.getById(patrolIntelligentEquip.getConstructionWorkSiteId());
                if(Objects.nonNull(constructionWorkSiteBean)){
                    constructionWorkAndWorkSiteInfoVO.setIfGrant(constructionWorkSiteBean.getIfGrant());
                }
            }
        }
        return constructionWorkAndWorkSiteInfoVO;
    }
    
    @Override
    public void sendDeviceBroadcastStatus(PatrolIntelligentEquipBroadcastStatusDTO statusDTO){

        if(StringUtils.isEmpty(statusDTO.getDeviceId()) || StringUtils.isEmpty(statusDTO.getChannelId())){
            log.error("发送设备喊话状态，信息不全，设备ID：{}，设备通道：{}", statusDTO.getDeviceId(), statusDTO.getChannelId());
            return;
        }

        List<PatrolIntelligentEquipChannel> intelligentEquipChannelList = intelligentEquipChannelService.lambdaQuery()
                .eq(PatrolIntelligentEquipChannel::getChannelCode, statusDTO.getChannelId())
                .list();
        
        if(CollectionUtils.isNotEmpty(intelligentEquipChannelList)){
            List<String> equipIdList = intelligentEquipChannelList.stream().map(PatrolIntelligentEquipChannel::getEquipId).distinct().collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(equipIdList)){
                List<PatrolIntelligentEquip> intelligentEquipList = this.lambdaQuery().in(PatrolIntelligentEquip::getObjId, equipIdList)
                        .eq(PatrolIntelligentEquip::getSipCode, statusDTO.getDeviceId())
                        .eq(PatrolIntelligentEquip::getDeleteState, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                        .list();
                if(CollectionUtils.isNotEmpty(intelligentEquipList)){
                    PatrolIntelligentEquip patrolIntelligentEquip = intelligentEquipList.get(0);

                    // 查询项目
                    String constructionWorkId = patrolIntelligentEquip.getConstructionWorkId();
                    String projectDepartmentObjId = constructionWorkService.findProjectDepartmentObjIdByObjId(constructionWorkId);
                    // 查询项目下的成员
                    List<String> userIdList = Lists.newArrayList();

                    // 总部管理员ID
                    List<String> headOfficeUserIdList = userService.findAllHeadOfficeUserId();
                    if (CollectionUtils.isNotEmpty(headOfficeUserIdList)) {
                        userIdList.addAll(headOfficeUserIdList);
                    }
                    
                    List<String> orgIdList = orgService.findAllParentObjIdByOrgId(projectDepartmentObjId);
                    if(CollectionUtils.isNotEmpty(orgIdList)){
                        List<String> tempUserIdList = userService.findProjectDepartmentAdminUserIdByProjectDepartmentIdIn(orgIdList);
                        if(CollectionUtils.isNotEmpty(tempUserIdList)){
                            userIdList.addAll(tempUserIdList);    
                        }
                    }

                    if(CollectionUtils.isEmpty(userIdList)){
                        log.error("发送设备喊话状态，用户不存在，不发送");
                        return;
                    }
                    BroadcastStatusVO statusVO = new BroadcastStatusVO();
                    statusVO.setMsgType(BaseCodeConstants.CodeType_WebSocketMsgType.KEY_WebSocketMsgType05);
                    statusVO.setEquipId(patrolIntelligentEquip.getObjId());
                    statusVO.setErrorMsg(statusDTO.getErrorMsg());
                    warnWebSocketService.sendMessage(JSON.toJSONString(statusVO), userIdList);
                }
            }
        }
    }
}
